在程序开发中,我们经常有写数据库表的操作,数据表中经常带有主键自增序列,如何获取自增序列。spring中提供了相应的类 DataFieldMaxValueIncrementer。
DataFieldMaxValueIncrementer 接口定义了3个获取下一个主键值的方法:
int nextIntValue(): 获取下一个主键值,主键数据类型为int;
long nextLongValue(): 获取下一个主键值,主键数据类型为long;
String nextStringValue(): 获取下一个主键值,主键数据类型为String;
在spring工程的spring-dao.xml中添加配置如下:
Oracle 配置
①指定序列名②设置数据源
MySQL 配置
①设置维护主键的表名②用于生成主键值的列名③缓存大小
代码中用时如下:
@Autowired
private DataFieldMaxValueIncrementer unitIniIncre;
//获取主键序列
long gid = unitIniIncre.nextLongValue();