假设我们要建两张表,学生信息表(student)和年级信息表(grade),关系是这样的:
我们可以看出学生表和=年级表是多对一的关系,多个学生会隶属于一个班级,这种关系在hibernate中成为单边的多对一的关系,需要这样配置:
新建实体类Grade:
public class Grade { private int id;
private String name;
private String teacher;
//get/set方法省略
}
新建实体类Student:
public class Student { private int id;
private String name;
private String sex;
private Grade grade;
//get/set方法省略
}
当前包下新建Grade类的映射文件Grade.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.wang.pojo">
<class name="Grade" >
<id name="id">
<generator class="native"></generator>
</id> <property name="name"></property>
<property name="teacher"></property>
</class>
</hibernate-mapping>
当前包下新建Student类的映射文件student.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.wang.pojo">
<class name="Student" >
<id name="id">
<generator class="native"></generator>
</id> <property name="name"></property>
<property name="sex"></property>
<!--
该标签配置多对一的关系
name:指定实体类中对应的属性
column:指定外键列名
class:指定属性所属的类
not-found:默认为exception,表示Gradebu不存在,则抛出异常,可以修改为ignore,忽略异常
cascade:制定级联保存选项, -->
<many-to-one name="grade" class="Grade" column="gradeId" ></many-to-one>
</class>
</hibernate-mapping>
新建一个测试类,测试生成数据库表以及向数据库表中添加数据:
@Test
public void testCreateDB() {
Configuration cfg = new Configuration().configure();
SchemaExport se = new SchemaExport(cfg);
// 第一个参数是否生成ddl脚本 第二个参数是否执行到数据库
se.create(true, true);
} @Test
public void testSave() {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
// Score s=new Score(2,12,97);
// session.save(s);
Grade g=new Grade(1, "初三一班", "王永");
session.save(g);
Student s=new Student("张三", "男", g);
session.save(s);
tx.commit();
session.close();
}