Hibernate中主键生成策略

主键生成策略:
1、identity
适合MySQL、DB2、SqlServer
2、sequence
适合oracle数据库
(1)添加oracle驱动
ojdbc14_11g.jar
(2)修改hibernate.cfg.xml信息
driver:oracle.jdbc.driver.OracleDriver
url:jdbc:oracle:thin:@192.168.0.26:1521:******
username:openlab
password:open123

<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">
jdbc:oracle:thin:@192.168.0.26:1521:tarena
</property>
<property name="connection.username">
openlab
</property>
<property name="connection.password">
open123
</property>

<property name="dialect">
org.hibernate.dialect.OracleDialect
</property>
(3)在oracle数据库中创建一个序列(sequence)
create sequence sequ_user_id;
(4)User.hbm.xml
<generator class="sequence">
<param name="sequence">sequ_user_id</param>
</generator>
sequ_user_id:序列名

3、native
代理主键,根据底层数据库的具体特征选择适合的主键生成策略,如果是mysql或者sqlserver,选择identity,如果是oracle,选择sequence
4、increment:hibernate生成主键
<id name="userId" column="user_id">
<!--
increment:hibernate生成主键
不在使用数据库中auto_increment
-->
<generator class="increment"/>
</id>
主键如何生成:
(1)获取select max(user_id) from t_user

(2)id=max(user_id)+1
(3)执行insert语句
5、assigned:程序员自己维护主键
<id name="userId" column="user_id">
<!-- assigned
不使用数据任何生成策略,主键有程序员维护
-->
<generator class="assigned"/>

</id>



你可能感兴趣的:(Hibernate)