天天看點

Spring 主鍵序列值擷取

先看個demo :

<bean id="unitImportService"
		class="net.zdsoft.eis.base.data.service.impl.UnitImportServiceImpl" init-method="initUnitImport">
		<property name="unitIncre">
			<bean
				class="org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer">
				<property name="incrementerName" value="s_unit_partition_num" />
				<property name="dataSource" ref="dataSource" />
			</bean>
		</property>
		<property name="unitIniIncre">
			<bean
				class="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_NUM
minvalue 1
maxvalue 999999999999999999999999999
start with 301
increment by 1
cache 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>