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