Hibernate之主键生成策略

今天分享是hibernate映射框架的主键自动生成器

一:Hibernate主键生成器

generator元素:表示了一个主键生成器,它用来为持久化类实例生成唯一的标识 。

1.1 程序员自己控制:assigned  (不管数据库中列段如何设置,最终控制权在程序员手中,他想干嘛就得干嘛

1.2 数据库控制: identity(标识列/自动增长) sequence(在hibernate内置的序列号默认的情况下所有关于hibernate的表都会使用,从而出现跳号的现象,不建议使用

1.3 hibernate控制:increment uuid/uuid.hex 

1.4 其它:native

二:主建生成器的要求

2.1 assigned
数据类型不限、保存前必须赋值

2.2 identity(重点掌握)
数字,无需赋值

2.3 sequence(重点掌握)
数字,无需赋值, 默认使hibernate_sequence这个序列,
也可以通过sequence/sequence_name参数赋值

2.4 increment
数字,无需赋值

2.5 uuid/uuid.hex (是由容器自动生成的一个32位的字符串,.hex代表的是十六进制)
32位的字符串,无需赋值,

2.6 native(重点掌握)
等于identity+sequence

三:展示案例

  首先设计两个表

学生表 t_hibernate_student

工人表 t_hibernate_worker

创建工具类SessionFactoryUtils,用来检测所写映射文件是否正确

 

package com.ht.two.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
 * 这个类是在学习hibernate的过程中所用(整合SSH框架之前用)
 * @author Administrator
 */
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类

package com.ht.two.entity;

import java.io.Serializable;

public class Student implements Serializable{
    private Integer sid;
    private String sname;
    public Integer getSid() {
        return sid;
    }
    public void setSid(Integer sid) {
        this.sid = sid;
    }
    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    
}

  worker类

package com.ht.two.entity;

public class Worker {

    private String wid;
    private String wname;
    public String getWid() {
        return wid;
    }
    public void setWid(String wid) {
        this.wid = wid;
    }
    public String getWname() {
        return wname;
    }
    public void setWname(String wname) {
        this.wname = wname;
    }
    @Override
    public String toString() {
        return "Worker [wid=" + wid + ", wname=" + wname + "]";
    }
    
}

在创建对应的映射文件

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.ht.two.entity.Student" table="t_hibernate_student">
        <id name="sid" type="java.lang.Integer" column="sid">
            <!-- <generator class="assigned" /> -->
            <generator class="identity" /><!--自增、标识列-->
<!--             <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>

Worker.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.ht.two.entity.Worker" table="t_hibernate_worker">
        <id name="wid" type="java.lang.String" column="wid">
            <!-- <generator class="assigned" /> -->
            <!-- <generator class="sequence" /> -->
            <!-- <generator class="sequence" > <param name="sequence_name">aaa</param> 
                </generator> -->
             <generator class="com.ht.two.id.Myst" />
        </id>

        <property name="wname" type="java.lang.String" column="wname">
        </property>
    </class>
</hibernate-mapping>

测试类

package com.ht.two.Dao;

import java.io.Serializable;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.ht.two.entity.Student;
import com.ht.two.entity.Worker;
import com.ht.two.util.SessionFactoryUtils;

public class DemoDao {

    /**
     * 添加学生
     * @param student
     * @return
     */
    public Serializable addStudent(Student student) {
        Session session=SessionFactoryUtils.openSession();
        Transaction transaction=session.beginTransaction();
        Serializable saveId=session.save(student);
        transaction.commit();
        session.close();
        return saveId;
    }
    /**
     * 添加工人
     * @param worker
     * @return
     */
    public Serializable addWorker(Worker worker) {
        Session session=SessionFactoryUtils.openSession();
        Transaction transaction=session.beginTransaction();
        Serializable saveId=session.save(worker);
        transaction.commit();
        session.close();
        return saveId;
    }
    /**
     * 学生测试
     * @param args
     */
    public static void main(String[] args) {
        DemoDao dao=new DemoDao();
        Student student=new Student();
//        student.setSid(5);
        student.setSname("青灯");
        System.out.println(dao.addStudent(student));
    }
    /**
     * 工人测试
     * @param args
     */
//    public static void main(String[] args) {
//        DemoDao dao=new DemoDao();
//        Worker worker=new Worker();
//        worker.setWid("1");
//        worker.setWname("hhhh");
//        System.out.println(dao.addWorker(worker));
//    }
}

自定义主建生成器

实现org.hibernate.id.IdentifierGenerator接口即可,并还可以实现org.hibernate.id.Configurable接口来读取一些配置信息
PersistentIdentifierGenerator.TABLE
PersistentIdentifierGenerator.PK

package com.ht.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 Myst implements IdentifierGenerator{

    @Override
    public Serializable generate(SharedSessionContractImplementor arg0, Object arg1) throws HibernateException {
        // TODO Auto-generated method stub
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return "daqing_youtian_ht_"+format.format(new Date());
    }

}

 

 

今日分享到此结束!!!谢谢观看!!!

 

posted @ 2019-07-14 20:22  沦陷  阅读(612)  评论(0编辑  收藏  举报