Learning Hibernate step by step -- 04 多对一关联关系映射
Java对象有很多关联关系映射,如多对一、一对一、多对多等,在数据库中表之间有主外键关联,Java对象的关联关系如何与数据表形成映射呢?首先来看多对一的映射关系。
一、背景
1. 一所学校有很多班级(Group),一个班级有若干学生(Student),学生和班级之间的映射就是多对一的关联关系,如图所示:
[img][/img]
2. 数据库中分别存在t_group表和t_student表,分别对应班级和学生,t_student表有一个外键,引用t_group的id字段,ER关系如图所示:
[img][/img]
二、建立域对象
1. 先在项目中建立两个独立的域对象,Group和Student,两个对象包含基本的信息,先不对两个对象做关联。两外再分别建立两个对象的Dao对象,负责与数据库交互。
Persistent.java
public class Persistent implements Serializable {private static final long serialVersionUID = 1L;private long id;public long getId() {return id;}public void setId(long id) {this.id = id;}}
public class Group extends Persistent {private static final long serialVersionUID = 1L;String grpName;public String getGrpName() {return grpName;}public void setGrpName(String grpName) {this.grpName = grpName;}}
public class Student extends Persistent {private static final long serialVersionUID = 1L;private String studNo;private String studName;private String studSex;public String getStudNo() {return studNo;}public void setStudNo(String studNo) {this.studNo = studNo;}public String getStudName() {return studName;}public void setStudName(String studName) {this.studName = studName;}public String getStudSex() {return studSex;}public void setStudSex(String studSex) {this.studSex = studSex;}}
public class GroupDao {public long saveGroup(Object obj) {Session session = HibernateUtil.getSessionFactory().openSession();Transaction tx = null;try {tx = session.beginTransaction();Long retId = (Long)session.save(obj);tx.commit();return retId.longValue();} catch (Exception e) {if (tx != null) {tx.rollback();}// DO NOT swallow the Exception in actual projects.// throw e;e.printStackTrace();return 0L;} finally {session.close();}}}
public class StudentDao {public long saveStudent(Object obj) {Session session = HibernateUtil.getSessionFactory().openSession();Transaction tx = null;try {tx = session.beginTransaction();Long retId = (Long)session.save(obj);tx.commit();return retId.intValue();} catch (Exception e) {if (tx != null) {tx.rollback();}// DO NOT swallow the Exception in actual projects.// throw e;e.printStackTrace();return 0L;} finally {session.close();}}}
<?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.foobar.domain"><class name="Group" table="`T_Group`"><comment>Groups infomation.</comment><id name="id"><generator not-null="true" column="`grp_name`"/></class></hibernate-mapping>
<?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.foobar.domain"><class name="Student" table="`T_Student`"><comment>Students infomation.</comment><id name="id"><generator length="15" column="`stud_name`"/><property name="studSex" not-null="true" length="1" column="`stud_sex`"/><many-to-one name="group" column="`group_id`"/></class></hibernate-mapping>
...<mapping resource="com/foobar/conf/hbm/Group.hbm.xml"/><mapping resource="com/foobar/conf/hbm/Student.hbm.xml"/>...
<!-- mapping与ddl之间的关系--><property name="hibernate.hbm2ddl.auto">create</property>
public class SchoolMgt {public static void main(String[] args) {GroupDao grpDao = new GroupDao();Group grp = new Group();StudentDao studDao = new StudentDao();Student stud = new Student();grp.setGrpName("Group A");if(grpDao.saveGroup(grp) != 0) {System.out.println("Group added successful!");}stud.setStudName("Zhangsan");stud.setStudNo("0001001");stud.setStudSex("F");if(studDao.saveStudent(stud) != 0) {System.out.println("Student added successful!");}}}
private Group group;// setter and getter
<many-to-one name="group" column="`group_id`"/>
...stud.setGroup(grp);...
<many-to-one name="propertyName" (1) column="column_name" (2) (3) cascade="cascade_style" (4) fetch="join|select" (5) update="true|false" (6) insert="true|false" (6) property-ref="propertyNameFromAssociatedClass" (7) access="field|property|ClassName" (8) unique="true|false" (9) not-null="true|false" (10) optimistic-lock="true|false" (11) lazy="proxy|no-proxy|false" (12) not-found="ignore|exception" (13) entity-name="EntityName" (14) formula="arbitrary SQL expression" (15) node="element-name|@attribute-name|element/@attribute|." embed-xml="true|false" index="index_name" unique_key="unique_key_id" foreign-key="foreign_key_name"/>