Hibernate多对一
?Many:
package com.domain;public class Employee {private int id;private String name;private Department depart;}?
One:
package com.domain;public class Department {private int id;private String name;}?
Employee.hbm.xml:
<?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.domain"><class name="Employee" discriminator-value="0"><id name="id"><generator /></id><property name="name" unique="true" /><many-to-one name="depart" column="depart_id" /></class></hibernate-mapping>
?
Department.hbm.xml:
<?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.domain"><class name="Department"><id name="id"><generator /></id><property name="name" /></class></hibernate-mapping>
?
?Many2One:
import org.hibernate.Session;import org.hibernate.Transaction;import com.dao.HibernateUitl;import com.domain.Department;import com.domain.Employee;public class Many2One {public static void main(String[] args) {add();}static Department add() {Session s = null;Transaction tx = null;try {Department depart = new Department();depart.setName("depart name");Employee emp = new Employee();emp.setDepart(depart);// 对象模型:建立两个对象的关联emp.setName("emp name");s = HibernateUitl.getSession();tx = s.beginTransaction();s.save(depart);s.save(emp);tx.commit();return depart;} finally {if (s != null)s.close();}}}?
?