hibernate--ID生成策略--XML

xml生成id,

a) generator

b) 常用4个: native, uuid, identity, sequence

1. 新建java项目,  引入hibernate, junit(user library)和sql包

2. 新建包 com.bjsxt.hibernate, class: Student.java:

package com.bjsxt.hibernate;

public class Student {
private int id;
private String name;
private int age; public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} }

3. 新建Student.hbm.xml:  使用generator class  , 换成uuid的话, 需要把 Student.java里的id改成String类型

<?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 package="com.bjsxt.hibernate">
<class name="Student" table="_student">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"/>
<property name="age"/>
</class>
</hibernate-mapping>

4. 配置hibernate.cfg.xml放在src下.    update重要, 否则不用新生成id

5. 创建log4j.properties在src下:

6. 项目右键新建source folder---"test"

7. 项目下新建package  com.bjsxt.hibernate, 和上面同名;

8. junit test文件里加入Studnet的测试代码

package com.bjsxt.hibernate;

import org.hibernate.HibernateException;
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 sf=null;
@BeforeClass
public static void beforeClass(){
try {
sf=new AnnotationConfiguration().configure().buildSessionFactory();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@AfterClass
public static void afterClass(){
sf.close();
} @Test
public void testStudentSave() {
Student s =new Student();
s.setName("wddddf");
s.setAge(23); Session session = sf.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
} @Test
public void testTeacherSave() {
Teacher t =new Teacher();
t.setName("wdf");
t.setTitle("higfdfsdfsadh"); Session session = sf.openSession();
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
session.close();
} }

9. run as->junit test, 就会自动递增id, 生成新纪录  

上一篇:BZOJ1563/洛谷P1912 诗人小G 【四边形不等式优化dp】


下一篇:可编辑的DIV -编辑器