Spring中獲取數據庫表主鍵序列


在程序開發中,我們經常有寫數據庫表的操作,數據表中經常帶有主鍵自增序列,如何獲取自增序列。spring中提供了相應的類 DataFieldMaxValueIncrementer。

  DataFieldMaxValueIncrementer 接口定義了3個獲取下一個主鍵值的方法:
  int nextIntValue():    獲取下一個主鍵值,主鍵數據類型為int;
  long nextLongValue():  獲取下一個主鍵值,主鍵數據類型為long;
  String nextStringValue(): 獲取下一個主鍵值,主鍵數據類型為String;

 在spring工程的spring-dao.xml中添加配置如下:

Oracle 配置

<bean id="incre" class="org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer">
    <property name="incrementerName" value="seq_post_id"/> ①指定序列名
    <property name="dataSource" ref="dataSource"/> ②設置數據源
</bean> 

MySQL 配置

<bean id="incre" class="org.springframework.jdbc.support.incrementer.MySQLMaxValueIncrementer">
    <property name="incrementerName" value="t_post_id"/> ①設置維護主鍵的表名
    <property name="columnName" value="sequence_id"/>②用於生成主鍵值的列名
    <property name="cacheSize" value="10"/> ③緩存大小
    <property name="dataSource" ref="dataSource"/>
</bean> 

代碼中用時如下:

@Autowired
private DataFieldMaxValueIncrementer unitIniIncre;

//獲取主鍵序列

long gid = unitIniIncre.nextLongValue();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM