Spring中獲得數據庫的自增主鍵值


  1. ...  
  2.     class Insert extends SqlUpdate {  
  3.   
  4.         private final Logger logger = Logger.getLogger(Insert.class);  
  5.   
  6.         public Insert(DataSource dataSource) {  
  7.             super(dataSource, INSERT_SQL);  
  8.             initInsertParams(this);  //初始化insert參數,與此處沒有直接關係  
  9.               
  10.             this.setReturnGeneratedKeys(true);  //設置可以返回主鍵信息  
  11.               
  12.             if(logger.isDebugEnabled())  
  13.                 logger.debug(" sql =" + this.getSql());  
  14.         }  
  15.     }  
  16.   
  17.     private Insert insert;  
  18.   
  19.     private synchronized void insert(Object obj) {  
  20.         Object[] values = getInsertValues(obj);  
  21.           
  22.         //返回的主鍵信息將保存在GeneratedKeyHolder的LinkedList中  
  23.         KeyHolder keyHolder = new GeneratedKeyHolder();  
  24.         this.insert.update(values, keyHolder);  
  25.           
  26.         ((ObjectId) obj).setId(keyHolder.getKey().longValue());  
  27.     }  
  28. ...  

以上是AbstractDao的部分代碼,提醒的一點是:如果在Spring中使用獲取最新自增主鍵值的查詢語句,比如MySQL的SELECT LAST_INSERT_ID()時,一定要注意SELECT LAST_INSERT_ID()是真對當前insert或update的Connection的,而Spring中每次操作是如此獲得Connection的【Connection con = DataSourceUtils.getConnection(getDataSource());】,所以如果不能正確使用會得不到自己想要的結果。

轉載自http://webwork.iteye.com/blog/361348

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章