业务需求:要求查询每个学生所在的班级
实体关联:学生类持有班级类的引用(省略setter getter方法)
public class Student {
private Integer id;
private String name;
Private Classes clazz;
}
public class Classes {
private Integer id;
private String name;
}
映射文件
Classes.hbm.xml
<hibernate-mapping package="cn.edu.bzu.hibernate.entity">
<class name="Classes" table="t_classes">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>
Student.hbm.xml
<hibernate-mapping>
<class name="cn.edu.bzu.hibernate.entity.Student" table="t_student">
<id name="id">
<generator class="native" />
</id>
<property name="name" />
<!--使用这个多对一标签描述引用>
<many-to-one name="clazz" class="cn.edu.bzu.hibernate.entity.Classes"></many-to-one>
</class>
</hibernate-mapping>
表结构
mysql> desc t_student;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| clazz | int(11) | YES | MUL | NULL | |
+-------+--------------+------+-----+---------+----------------+
mysql> desc t_classes;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
+-------+--------------+------+-----+---------+----------------+
测试方法
@Test
public void testSave1() {
Session session = null;
try {
session = HibernateSessionFactory.getSession();
session.beginTransaction();
Classes clazz = new Classes();
clazz.setName("class1");
session.save(clazz);
Student student1 = new Student();
student1.setName("test");
student1.setClazz(clazz);
Student student2 = new Student();
student2.setName("testj");
student2.setClazz(clazz);
session.save(student1);
session.save(student2);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
} finally {
HibernateSessionFactory.closeSession();
}
}
测试结果:
create table t_classes (id integer not null auto_increment, name varchar(255), primary key (id))
create table t_student (id integer not null auto_increment, name varchar(255), clazz integer, primary key (id))
alter table t_student add index FK4B9075708C142E7B (clazz), add constraint FK4B9075708C142E7B foreign key (clazz) references t_classes (id)
SchemaUpdate:217 - schema update complete
Hibernate: insert into t_classes (name) values (?)
Hibernate: insert into t_student (name, clazz) values (?, ?)
Hibernate: insert into t_student (name, clazz) values (?, ?)