码迷,mamicode.com
首页 > Web开发 > 详细

hibernate之主键生成策略

时间:2019-08-03 18:45:35      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:system   image   share   nsa   线程   imp   hbm   student   www   

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

连接数据库的xml

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/sys?useUnicode=true&amp;characterEncoding=UTF-8
        </property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</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/jt/entity/User.hbm.xml"/>
        <!--主键生成策略  -->
        <mapping resource="com/jt2/entity/Student.hbm.xml"/>
        <mapping resource="com/jt2/entity/Worker.hbm.xml"/>
       </session-factory>
    </hibernate-configuration>

 

Student.java

package com.jt2.entity;

public class Student {

    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;
    }
    public Student(Integer sid, String sname) {
        super();
        this.sid = sid;
        this.sname = sname;
    }
    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }
    @Override
    public String toString() {
        return "Student [sid=" + sid + ", sname=" + sname + "]";
    }
    
}

Worker.java

package com.jt2.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;
    }
    public Worker(String wid, String wname) {
        super();
        this.wid = wid;
        this.wname = wname;
    }
    public Worker() {
        super();
        // TODO Auto-generated constructor stub
    }
    @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.jt2.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="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.jt2.entity.Worker" table="t_hibernate_worker">
        <id name="wid" type="java.lang.String" column="wid">
            <!-- <generator class="assigned" /> -->
            <!-- <generator class="sequence" /> -->
            <!-- <generator class="uuid" /> -->
            <generator class="com.jt2.id.MyTsGenerator" />
            <!-- <generator class="sequence" /> -->
            <!-- <generator class="sequence" > <param name="sequence_name">aaa</param> 
                </generator> -->
            <!-- <generator class="com.javaxl.two.id.Myts" /> -->
        </id>

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

 

 

还有个工具类

SessionFactoryUtils.java

package com.jt2.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
 * 仅在学习hibernate的工程中使用,当进入spring的学习后就没用了,
 * 后面会有ssh来代替它
 * 
 * 作用:
 *   用来检测hibernate中的配置文件的准确性
 *       hibernate.cfg.xml
 *       *.hbn.xml
 * @author jt
 *
 */
public class SessionFactoryUtils {
    private static SessionFactory sessionFactory;
    static {
        Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
        sessionFactory = cfg.buildSessionFactory();
    }
    
    public static Session openSession() {
        //从本地的线程中获取session会话,第一次肯定是获取不到的,那么需要重新让sessionfactory创建一个session出来
        //第二次就能够对第一次创建的session反复利用,节约性能
        Session session = sessionFactory.getCurrentSession();
        if(session == null) {
            session = sessionFactory.openSession();
        }
        return session;
    }
    
    public static void closeSession() {
        Session session = sessionFactory.getCurrentSession();
        if(session != null && session.isOpen()) {
            session.close();
        }
    }
    
    public static void main(String[] args) {
        Session session = SessionFactoryUtils.openSession();
        session.beginTransaction();
        System.out.println(session.isConnected());
        SessionFactoryUtils.closeSession();
        System.out.println(session.isConnected());
    }
}

 

做测试用dao层做我们建一个

DemoDao.java

package com.jt2.dao;

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

import com.jt2.entity.Student;
import com.jt2.entity.Worker;
import com.jt2.util.SessionFactoryUtils;
/**
 * hibernate中的主键生成策略
 * 1,人工控制
 * 2,数据库控制
 * 3,hibrenate控制
 * 4,自定义主键生成策略
 * @author jt
 *
 */
public class DemoDao {

    /**
     * 新增学生
     * @param stu
     */
    public void addStudent(Student stu) {
        Session session = SessionFactoryUtils.openSession();
        Transaction transaction = session.beginTransaction();
        session.save(stu);
        transaction.commit();
        SessionFactoryUtils.closeSession();
    }
    /**
     * 新增功能
     * @param worker
     */
    public void addWorker(Worker worker) {
        Session session = SessionFactoryUtils.openSession();
        Transaction transaction = session.beginTransaction();
        session.save(worker);
        transaction.commit();
        SessionFactoryUtils.closeSession();
    }
    public static void testStudent(String[] args) {
        DemoDao dao=new DemoDao();
        Student stu=new Student();
        stu.setSname("哈哈哈");
        stu.setSid(71);
        dao.addStudent(stu);
    }
    
    public static void main(String[] args) {
        DemoDao dao=new DemoDao();
        Worker worker=new Worker();
        worker.setWname("jt");
        dao.addWorker(worker);
    }
    
}

技术图片

技术图片

最后建一个

 MyTsGenerator.java

package com.jt2.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 MyTsGenerator implements IdentifierGenerator {

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
        return "book_order_"+sdf.format(new Date());
    }

}

 

 然后我们把DemoDao.java里面的的测试数据改下

技术图片

技术图片

 

 这就是成功了,今天就到这里了

 

hibernate之主键生成策略

标签:system   image   share   nsa   线程   imp   hbm   student   www   

原文地址:https://www.cnblogs.com/ztbk/p/11295777.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!