首页 > 代码库 > hibernate主键生成策略

hibernate主键生成策略

主键生成采用uuid的方式生成,在实体类中该主键的类型必须为String类型。

 

hibernate xml配置文件的方式

实体类:Student.java:

package com.bxw.entity;

public class Student {
    private String id;
    private String name;
    private String sex;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    
    
}

配置文件Student.hbm.xml默认路径和Student类在同一个包。

<?xml version="1.0" encoding=‘UTF-8‘?>  
  
<!DOCTYPE hibernate-mapping PUBLIC   
     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"   
     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
<hibernate-mapping package="com.bxw.entity">  
   <class name="Student">  
      <id name="id">
          <generator class="uuid"></generator>
      </id> 
      <property name="name"></property>  
      <property name="sex"></property>  
   </class>
</hibernate-mapping>  

测试

package com.bxw.test;

import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.bxw.entity.Student;

public class StudentTest{
    private static Session session = null;

    @BeforeClass
    public static void getSession(){
        try {
            Configuration conf = new Configuration();
            conf.configure();
            session = conf.buildSessionFactory().openSession();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Test
    public void hibernateIdTest() {
        Student ss = new Student();
        ss.setName("Han meimei");
        ss.setSex("女");
        
        session.beginTransaction();
        session.save(ss);
        session.getTransaction().commit();
    }
    
    @AfterClass
    public static void over(){
        session.close();
    }
}

 

hibernate主键生成策略