我試圖向MySQL表中插入一行並獲取其插入ID。我意識到MySQL last_insert_id()
函數,我似乎無法讓它工作。目前,我正在嘗試使用註釋爲事務的函數,並且只返回0。我正在使用Spring 3.1。Spring JdbcTemplate無法從MySQL獲取插入ID
@Transactional (propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
private long insertTransactionRecord
(
int custID,
int porID,
String date,
short crvID
) {
m_template.update ("INSERT INTO " +
" transaction " +
"(" +
" por_id, " +
" cust_id, " +
" trans_date, " +
" crv_id " +
") " +
"VALUES " +
"(" +
" ?, " +
" ?, " +
" ?, " +
" ? " +
")",
new Object[] {
porID,
custID,
date,
crvID
});
return m_template.queryForLong ("SELECT " +
" last_insert_id() " +
"FROM " +
" transaction " +
"LIMIT 1");
}
「FROM」子句的用途是指定我想要的ID表。 'JdbcTemplate'使用連接池,所以我不能保證在同一個連接上。這筆交易本應彌補這一點。謝謝你的建議,但沒有幫助。 – Nik 2012-02-19 16:35:08
使用jdbcTemplate.queryForObject(「select last_insert_id()」,Integer.class) – singhspk 2013-12-04 14:00:33
我不認爲這種方法是線程安全的,是嗎? queryForInt(..)調用可能在發生多次插入後發生,並在其上面插入語句時返回錯誤的ID。 – 2015-01-03 17:53:55