以学生Student和班级Clazz多对一为例(单向多对一)
//Clazz类
public class Clazz {
private Integer id;
private String cname;
//省略setter和getter
}
//Student类
public class Student {
private Integer id;
private String sname;
//多对一关系
private Clazz clazz;
//省略setter和getter
}
<!--Clazz.hbm.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="join.model.Clazz" table="CLAZZ">
<id name="id" column="ID">
<generator class="increment"></generator>
</id>
<property name="cname" column="CNAME"></property>
</class>
</hibernate-mapping>
<!--Student.hbm.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="join.model.Student" table="STUDENT">
<id name="id" column="ID">
<generator class="increment"></generator>
</id>
<property name="sname" column="SNAME"></property>
<!-- 多对一 -->
<!--
name:对类中pojo类型属性的说明(即对一方的说明)
class:对pojo类型说明
column:指定关联外键
-->
<many-to-one name="clazz" class="join.model.Clazz" column="CID"></many-to-one>
</class>
</hibernate-mapping>
//StudentDao
public class StudentDao {
public Student selectById(Integer id){
Session session = HibernateUtil.findSession();
return session.get(Student.class, id);
}
}
//StudentService
public class StudentService {
private StudentDao dao = new StudentDao();
public Student findById(int id) {
Session session = HibernateUtil.findSession();
Transaction tx = session.beginTransaction();
Student stu = null;
try {
stu = dao.selectById(id);
// tx.commit();
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
}
return stu;
}
}
//测试
@Test
public void testFindStudent() {
Student stu = ser2.findById(1);
System.out.println(stu.getId() + "," + stu.getSname());
System.out.println(stu.getClazz().getCname());
}