首页 > 技术文章 > 深入浅出Hibernate(二)多对一关系映射

blfbuaa 2017-07-10 17:32 原文

     学习Hibernate是为了更方便的操作数据库,在数据库中的关系模型中存在多对一的关系,比方下图所看到的的员工和部门之间的关系,那么这样的关系在Hibernate中怎样映射呢?让我用一个小Demo来具体解说。

   

     建立映射分为下面几步:

   1.设计domain对象Department、Employee,代码例如以下:

package cn.itcast.hibernate.domain;

public class Department {
	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
package cn.itcast.hibernate.domain;

public class Employee {
	private int id;
	private String name;
	private Department depart;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Department getDepart() {
		return depart;
	}
	public void setDepart(Department depart) {
		this.depart = depart;
	}
}

       2.导入hibernate.jar和其依赖的包,jar包的下载地址在上面博客中已经提供。这里不再赘述。

    3.编写Department.hbm.xml和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="cn.itcast.hibernate.domain">  
    <class name="Department" table="Department">  
        <id name="id">  
            <generator class="native"/>  
        </id>  
        <property name="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="cn.itcast.hibernate.domain">   
    <class name="Employee" table="Employee">  
        <id name="id">  
            <generator class="native"/>  
        </id>  
        <property name="name"/>  
        
        <many-to-one name="depart" column="depart_id"/>
    </class>  
</hibernate-mapping>  
     Employee.hbm.xml中的“many-to-one”部分是重点。通过它建立Department对象和Employee的关联关系。

    4.编写hibernate.cfg.xml配置文件,代码实现例如以下:

<!DOCTYPE hibernate-configuration PUBLIC  
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<property name="show_sql">true</property>
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
		<property name="connection.username">root</property>
		<property name="connection.password"></property>
		<property name="hbm2ddl.auto">update</property>
		
		<mapping resource="com/entity/User.hbm.xml" />
		<mapping resource="cn/itcast/hibernate/domain/Department.hbm.xml" />
		<mapping resource="cn/itcast/hibernate/domain/Employee.hbm.xml" />
	</session-factory>
</hibernate-configuration> 
   5.编写HibernateUtils类,主要用来完毕Hibernate初始化和提供一个获得Session的方法。代码实现例如以下:
package com.entity;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public final class HibernateUtil {
	private static SessionFactory sessionFactory;
	
	private HibernateUtil(){
	}
	
	static {
		//解析配置文件,完毕Hibernate初始化
		Configuration cfg=new Configuration();
		cfg.configure();
		//全部的信息在sessionFactory中都能够找到
		sessionFactory=cfg.buildSessionFactory();
	}
	
	public static SessionFactory getSesssionFactory(){
		return sessionFactory;
	}
	
	public static Session getSession(){
		return sessionFactory.openSession();
	}
}
    6.编写Main方法。通过操作Department类和Employee类,向数据库中写入数据,代码实现例如以下:
package com.entity;

import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.itcast.hibernate.domain.Department;
import cn.itcast.hibernate.domain.Employee;

public class Many2One {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		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 = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.save(depart);
			s.save(emp);
			tx.commit();
			return depart;
		} finally {
			if (s != null)
				s.close();
		}
	}
}
     让我们查看一下数据表的变化,效果图例如以下所看到的:

     
   通过上述方法。我们就能够轻松完毕多对一关系从关系模型到对象模型的映射,完美的体现了ORM的思想。

   希望我的解说能帮助大家学习Hibernate。

推荐阅读