问题描述:
Hibernate中Oracle自增长列怎样设定。
Oracle中我已经建了一列名为sequence_person的数据库自增长序列.
我在ApplicationContext.xml中怎么配?
问题解答:
步骤如下,(不是在ApplicationContext,而是那个表对应的.hbm.xml文件中配置
1、创建表
CREATE TABLE T_CUST(
CUST_ID INT NOT NULL,
CUST_NAME VARCHAR2(20) NOT NULL,
CONSTRAINT PK_T_CUST PRIMARY KEY (CUST_ID)
);
2、创建序列
CREATE SEQUENCE S_CUST_ID
MINVALUE 1
MAXVALUE 10000000
START WITH 1
INCREMENT BY 1
NOCACHE;
3、试试序列是否起作用
INSERT INTO T_CUST(CUST_ID, CUST_NAME) VALUES(S_CUST_ID.NEXTVAL, 'hahaha');
SELECT * FROM T_CUST;
结果:
|CUST_ID|CUST_NAME|
|1 |hahaha |
4、配置TCust.hbm.xml文件
<hibernate-mapping>
<class name="demo.hb.sequence.Cust" table="T_CUST" schema="DEMO">
<id name="custId" type="java.lang.Long">
<column name="CUST_ID" precision="22" scale="0" />
<!-- 使用Oracle Sequence的重点 -->
<generator class="sequence">
<!-- Oracle Sequence的名字 -->
<param name="sequence">S_CUST_ID</param>
</generator>
</id>
<property name="custName" type="java.lang.String">
<column name="CUST_NAME" length="20" not-null="true" />
</property>
</class>
</hibernate-mapping>
用序列,配置的例子如下:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.ctl.smartone.model.AclCategory" table="ACL_CATEGORY" dynamic-insert="true" dynamic-update="true">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="sequence">
<param name="sequence">SEQ_ACL_CATEGORY</param>
</generator>
</id>
<property name="name" type="java.lang.String">
<column name="CATEGORY_NAME" not-null="true" unique="false" />
</property>
<many-to-one name="parentCategory"
class="com.ctl.smartone.model.AclCategory">
<column name="PARENT_ID" />
</many-to-one>
<set name="childCategories" cascade="all" lazy="true">
<key column="PARENT_ID" />
<one-to-many class="com.ctl.smartone.model.AclCategory" />
</set>
<set name="aclUsers" cascade="all" lazy="true" inverse="true">
<key column="CATEGORY_ID" />
<one-to-many class="com.ctl.smartone.model.AclUser"/>
</set>
</class>
</hibernate-mapping>
<!--
CREATE TABLE SO_DASHBOARD
(
ID INT AUTO_INCREMENT not null,
BOARD_NAME VARCHAR(50) null,
XML_CONFIG VARCHAR(800) null,
primary key (ID)
)
ENGINE = InnoDB;
-->