很多情况下,一个数据库表中数据的id是自动生成的,且一般设为自动递增,hibernate便完成了这个功能。
Student.hbm.xml中的generator有四个生成策略:
native identity sequence uuid
新建一个Junit test:
HibernateIDTest 测试类中代码如下:
package com.mym.hibernate.model;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class HibernateIDTest {
private static SessionFactory sessionFactory;
@BeforeClass
public static void beforeClass(){
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
@AfterClass
public static void afterClass(){
sessionFactory.close();
}
@Test
public void testStudentSave(){
Student s = new Student();
s.setName("sa");
s.setAge(8);
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
}
public static void main(String[] args) {
beforeClass();
}
}
情况一:
在Student.hbm.xml中给id配置
<
generator
class
=
""
/>属性,其中的class值我们可以先取uuid
Student.hbm.xml中的代码如下:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping >
<class name="com.mym.hibernate.model.Student" >
<id name="id">
<generator class="uuid"/>
</id>
<property name="name" />
<property name="age"/>
</class>
</hibernate-mapping>
因为uuid默认是生成String类型的数据,所以在Student类中定义的id及get、set方法需要更改数据类型。
测试后:
可以看出,生成的id为一个string类型的字符串
情况二:
在Student.hbm.xml中给id配置
<
generator
class
=
""
/>属性,其中的class值我们可以先取native
Student.hbm.xml中的代码如下:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping >
<class name="com.mym.hibernate.model.Student" >
<id name="id">
<generator class="native"/>
</id>
<property name="name" />
<property name="age"/>
</class>
</hibernate-mapping>
native的默认是生成int类型的序号,但只更改class类型,hibernate不会自动在数据库生成表。为什么要重新生成表呢?或许是因为,不同的id类型,不能存在同一个实体类中,或者说不能存在同一个数据库表中。
所以,在执行测试类前,需要先删除原有的数据库。
测试后: