• hibernate之主键生成策略


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


    1.1 程序员自己控制:assigned

    1.2 数据库控制: identity(标识列/自动增长) sequence

    1.3 hibernate控制:increment uuid/uuid.hex

    连接数据库的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&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/zl/entity/User.hbm.xml"/>
            <!--主键生成策略  -->
            <mapping resource="com/zl2/entity/Student.hbm.xml"/>
            <mapping resource="com/zl2/entity/Worker.hbm.xml"/>
           </session-factory>
        </hibernate-configuration>
    

      

    Student.java

    package com.zl2.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.zl2.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.zl2.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.zl2.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.zl2.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.zl2.util;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    /**
     * 仅在学习hibernate的工程中使用,当进入spring的学习后就没用了,
     * 后面会有ssh来代替它
     * 
     * 作用:
     *   用来检测hibernate中的配置文件的准确性
     *       hibernate.cfg.xml
     *       *.hbn.xml
     * @author zl
     *
     */
    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.zl2.dao;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    
    import com.zl2.entity.Student;
    import com.zl2.entity.Worker;
    import com.zl2.util.SessionFactoryUtils;
    /**
     * hibernate中的主键生成策略
     * 1,人工控制
     * 2,数据库控制
     * 3,hibrenate控制
     * 4,自定义主键生成策略
     * @author zl
     *
     */
    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("zl");
            dao.addWorker(worker);
        }
        
    }
    

     

     MyTsGenerator.java

    package com.zl2.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

    public static void main(String[] args) {
    		DemoDao dao=new DemoDao();
    		Worker worker=new Worker();
    		worker.setWname("哈哈哈");
    		dao.addWorker(worker);
    	}
    

      

     

  • 相关阅读:
    打造vim IDE
    Shell常用快捷键
    centos修改SSH端口并禁用root远程登录
    Java集合图谱
    github密钥
    创建Node.js TypeScript后端项目
    Shell的类型
    Mac新系统常用设置
    mac svn无法保存密码,JetBrains IDE(WebStrom、IntelliJ IDEA) 反复提示输入密码
    vim快捷键
  • 原文地址:https://www.cnblogs.com/BAYOUA/p/11290956.html
Copyright © 2020-2023  润新知