这样获取MySql刚插入的ID(自增ID)有问题吗?
我在MySql的API里看到last_insert_id()可以返回上一次插入的数据的ID
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
然后我写了一个在Hibernate中用原生SQL插入数据后获取刚插入的数据的ID的方法如下:
public Integer batchSave(Session session, String insertSql, String tableName){ Transaction tx = session.beginTransaction(); Integer result = -1; String queryString = "SELECT last_insert_id() FROM "+tableName+" LIMIT 1;"; try { tx.begin(); result = [color=#FF0000]session.createSQLQuery(insertSql).executeUpdate();[/color] session.flush(); tx.commit(); if(result > 0) return(new Integer([color=#FF0000]session.createSQLQuery(queryString).list()[/color].get(0).toString())); } catch (DataAccessException e) { e.printStackTrace(); if (tx != null) { tx.rollback(); } } return null; }