Spring 主键序列值获取

来源:互联网 发布:mac windows抹掉 编辑:程序博客网 时间:2024/05/21 09:22

先看个demo :

<bean id="unitImportService"class="net.zdsoft.eis.base.data.service.impl.UnitImportServiceImpl" init-method="initUnitImport"><property name="unitIncre"><beanclass="org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer"><property name="incrementerName" value="s_unit_partition_num" /><property name="dataSource" ref="dataSource" /></bean></property><property name="unitIniIncre"><beanclass="org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer"><property name="incrementerName" value="s_stusys_systemini_unit" /><property name="dataSource" ref="dataSource" /></bean></property></bean>

我的Oracle数据库里面有个序列号 :

-- Create sequence create sequence S_UNIT_PARTITION_NUMminvalue 1maxvalue 999999999999999999999999999start with 301increment by 1cache 20;

在java文件使用如下:

private DataFieldMaxValueIncrementer unitIniIncre;unitIni.setId(unitIniIncre.nextLongValue());


根据不同的主键产生方式,可能需要配置表名、主键字段名或序列名等信息。下面,我们以Oracle和MySql为例分别讲解使用序列及表字段产生主 键值的方式。

  DataFieldMaxValueIncrementer接口定义了3个获取下一个主键值的方法:

  l int nextIntValue():获取下一个主键值,主键数据类型为int;

  l long nextLongValue():获取下一个主键值,主键数据类型为long;

  l String nextStringValue():获取下一个主键值,主键数据类型为String;

 

一般数据库都提供了自增键的功能,如MySql的auto_increment、SqlServerr的identity字段等。Spring允许你在应 用层产生主键值,为此定义了 org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer 接口,提供两种产生主键的方案:第一,通过序列产生主键;第二,通过表产生主键。

 

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>

0 0
原创粉丝点击