Hibernate之主键生成策略
程序员文章站
2022-06-12 19:31:45
...
Hibernate之主键策略
Hibernate要求实体类里面有一个属性作为唯一值,对应表主键。
Hibernate的主键生成器要求
主键生成器要求 | |
---|---|
generator | 表示了一个主键生成器,它用来为持久化类实例生成唯一的标识 。 |
assigned | 数据类型不限、保存前必须赋值 |
identity | 数字,无需赋值 (重点掌握) |
sequence | 数字,无需赋值, 默认使hibernate_sequence这个序列,或者通过sequence/sequence_name参数赋值 |
increment | 数字,无需赋值 |
uuid/uuid.hex | (是由容器自动生成的一个32位的字符串,.hex代表的是十六进制)32位的字符串,无需赋值, |
native | 等于identity+sequence |
主键生成策略
increment | 自动递增方式,每次增量为1 |
---|---|
sequence | Oracle数据库使用 |
identity | 主键生成标识符,支持自动增长,在DB2、MySQL、 MSSQL、sybase 和HypersonicSQL数据库中使用 |
native | 根据使用的数据库帮选择哪个值( 自动生成) identity、 sequence、 hilo三种生成- -种由后台数据库生成主键:默认生成的序列名称为: Hibernate Sequence。 |
uuid | 自动生成标识符,长度32位的16进制符,使用uuid生成策略,实体类id属性类型必须字符串类型。 |
下面就时主键实现主键实现步骤
首先配置核心文件hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 1. 数据库相关 -->
<property name="connection.username">root</property>
<property name="connection.password">123</property>
<property name="connection.url">jdbc:mysql://localhost:3306/tb_ttt?useUnicode=true&characterEncoding=UTF-8
</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- MySQL语言 -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- Oracle语言 -->
<!-- <property name="dialect">org.hibernate.dialect.OracleDialect</property> -->
<!-- 自动生成sequence_name序列表 -->
<property name="hbm2ddl.auto">update</property>
<!-- 配置本地事务(No CurrentSessionContext configured!) -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- 2. 调试相关 -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 3. 添加实体映射文件 -->
<mapping resource="com/tzp/one/entity/User.hbm.xml"/>
<!-- 讲解主键生成策略 -->
<mapping resource="com/tzp/two/entity/Student.hbm.xml"/>
<mapping resource="com/tzp/two/entity/Worker.hbm.xml"/>
</session-factory>
</hibernate-configuration>
加入一个辅助类,用于检测映射文件的配置是否正确
package com.tzp.two.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* 这个类是在学习hibernate的过程中所用(整合ssh框架之前应用)
*
*
* 作用:
* 可以用来检测所写的映射文件是否正确
* @author 20190320
*
*/
public class SessionFactoryUtils {
private static SessionFactory sessionFactory;
// 存放当前会话
private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
static {
Configuration cfg = new Configuration();
Configuration configure = cfg.configure("/hibernate.cfg.xml");
sessionFactory = configure.buildSessionFactory();
}
public static Session openSession() {
Session session = threadLocal.get();
if (null == session) {
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
public static void closeSession() {
Session session = threadLocal.get();
if (null != session) {
if (session.isOpen()) {
session.close();
}
threadLocal.set(null);
}
}
public static void main(String[] args) {
Session session = openSession();
System.out.println(session.isConnected());
closeSession();
}
}
建两个实体类,Student Worker
在分别配置它们的映射文件
Student.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.tzp.two.entity.Student" table="tb_student">
<id name="sid" type="java.lang.Integer" column="sid">
<generator class="increment" />
<!-- <generator class="increment" /> -->
<!-- <generator class="sequence" /> -->
<!-- <generator class="sequence" > <param name="sequence_name">aaa</param>
</generator> -->
<!-- <generator class="com.javaxl.two.id.Myts" /> -->
</id>
<property name="sname" type="java.lang.String" column="sname">
</property>
</class>
</hibernate-mapping>
准备工作做完了,接下来就是写dao方法了
package com.tzp.two.dao;
import java.io.Serializable;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.yz.two.entity.Student;
import com.yz.two.entity.Worker;
import com.yz.two.util.SessionFactoryUtils;
public class DemoDao {
public Serializable addStudent(Student stu) {
Session session = SessionFactoryUtils.openSession();
Transaction transaction = session.beginTransaction();
Serializable saveId = session.save(stu);
transaction.commit();
session.close();
return saveId;
}
/**
* 添加工人
* @param worker
* @return
*/
public Serializable addWork(Worker worker) {
Session session = SessionFactoryUtils.openSession();
Transaction transaction = session.beginTransaction();
Serializable saveId = session.save(worker);
transaction.commit();
session.close();
return saveId;
}
public static void testStudent(String[] args) {
DemoDao dao = new DemoDao();
Student stu = new Student();
stu.setSname("dabao");
dao.addStudent(stu);
System.out.println(dao.addStudent(stu));
}
public static void main(String[] args) {
DemoDao dao = new DemoDao();
Worker worker = new Worker();
worker.setWname("dabao");
dao.addWork(worker);
System.out.println(dao.addWork(worker));
}
}
输出效果
下面展示Student的数据库增加
例子:利用uuid生成主键添加数据
worker.hbm.xml,建好Worker实体类
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.tzp.two.entity.Worker" table="tb_worker">
<id name="wid" type="java.lang.String" column="wid">
<!--<generator class="uuid" /> -->
<!-- <generator class="sequence" /> -->
<!-- <generator class="sequence" > <param name="sequence_name">aaa</param>
</generator> -->
<generator class="com.tzp.two.id.Myts" />
</id>
<property name="wname" type="java.lang.String" column="wname">
</property>
</class>
它的方法在上面Demodao中,看输出效果
在写一个自定义主键生成器:
package com.tzp.two.id;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
public class Myts implements IdentifierGenerator {
@Override
public Serializable generate(SharedSessionContractImplementor arg0, Object arg1) throws HibernateException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return "xzy_shop_book_" + sdf.format(new Date());
}
}
worker的表增加数据成功