JFinal保存對象後能夠取出主鍵,即便這個主鍵是數據庫自增加的。sql
今天無心中發現,JFinal保存對象後能夠把主鍵取出來,個人數據庫表主鍵都是自增的。好比數據庫
Blog blog = getModel(Blog.class);//這裏沒有存放id
blog.save();
System.out.println(blog.getInt("id"));//這裏竟然能夠取出來。ui
今天研究的半天,最後在你們的幫助下終於明白是怎麼實現的了。Model類的源碼以下:this
public boolean save() {
Config config = getConfig();
Table table = getTable();
StringBuilder sql = new StringBuilder();
List<Object> paras = new ArrayList<Object>();
config.dialect.forModelSave(table, attrs, sql, paras);
// if (paras.size() == 0) return false; // The sql "insert into tableName() values()" works fine, so delete this line
// --------
Connection conn = null;
PreparedStatement pst = null;
int result = 0;
try {
conn = config.getConnection();
if (config.dialect.isOracle())
pst = conn.prepareStatement(sql.toString(), new String[]{table.getPrimaryKey()});
else
pst = conn.prepareStatement(sql.toString(), Statement.RETURN_GENERATED_KEYS);
config.dialect.fillStatement(pst, paras);
result = pst.executeUpdate();
getGeneratedKey(pst, table);
getModifyFlag().clear();
return result >= 1;
} catch (Exception e) {
throw new ActiveRecordException(e);
} finally {
config.close(pst, conn);
}
}spa
根據波總的指導,紅色加粗的代碼纔是保存後取出主鍵的關鍵,而綠色加粗部分是具體實現過程。通過查看API,這個方法是爲了建立一個默認 PreparedStatement
對象,該對象能獲取自動生成的鍵。給定常量告知驅動程序是否能夠獲取自動生成的鍵。若是 SQL 語句不是一條 INSERT
語句,或者 SQL 語句可以返回自動生成的鍵(這類語句的列表是特定於供應商的),則忽略此參數【JDK中文文檔的原話】。code
綠色加粗部分的源代碼:對象
/**
* Get id after save method.
*/
private void getGeneratedKey(PreparedStatement pst, Table table) throws SQLException {
String pKey = table.getPrimaryKey();
if (get(pKey) == null || getConfig().dialect.isOracle()) {
ResultSet rs = pst.getGeneratedKeys();
if (rs.next()) {
Class colType = table.getColumnType(pKey);
if (colType == Integer.class || colType == int.class)
set(pKey, rs.getInt(1));
else if (colType == Long.class || colType == long.class)
set(pKey, rs.getLong(1));
else
set(pKey, rs.getObject(1)); // It returns Long object for int colType
rs.close();
}
}
}blog