Spring中获取数据库表主键序列

在程序开发中,咱们常常有写数据库表的操做,数据表中常常带有主键自增序列,如何获取自增序列。spring中提供了相应的类 DataFieldMaxValueIncrementer。spring

  DataFieldMaxValueIncrementer 接口定义了3个获取下一个主键值的方法:
  int nextIntValue():    获取下一个主键值,主键数据类型为int;
  long nextLongValue():  获取下一个主键值,主键数据类型为long;
  String nextStringValue(): 获取下一个主键值,主键数据类型为String;数据库

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

Oracle 配置post

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

MySQL 配置spa

<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> 

代码中用时以下:code

@Autowired
private DataFieldMaxValueIncrementer unitIniIncre;xml

//获取主键序列blog

long gid = unitIniIncre.nextLongValue();接口

相关文章
相关标签/搜索