Hibernate ManyToOne Mappings 多对一关联映射

Hibernate框架的使用步骤:

1、创建Hibernate的配置文件(hibernate.cfg.xml)

2、创建持久化类,即其实例需要保存到数据库中的类(Employee.java)

3、创建对象-关系映射文件(Employee.hbm.xml)

4、通过Hibernate API编写访问数据库的代码

例子:多个员工对应一个地址。

一、创建hibernate.cfg.xml 配置文件:

注意数据库名、用户名、密码是否填写正确。

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

		<!-- Assume testone is the database name -->
		<property name="hibernate.connection.url">jdbc:mysql://localhost/testMany2One</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		<property name="hibernate.show_sql">true</property>

		<!-- List of XML mapping files -->
		<mapping resource="resource/Employee.hbm.xml" />

	</session-factory>
</hibernate-configuration>

二、创建持久化类,即其实例需要保存到数据库中的类(Employee.java、Address.java)

Employee.java

package com.jiangge.hblearn;

/**
 * @author jiangge
 */
public class Employee
{
	private int id;
	private String firstName;
	private String lastName;
	private int salary;
	private Address address;

	public Employee()
	{
	}

	public Employee(String firstName, String lastName, int salary,
			Address address)
	{
		this.firstName = firstName;
		this.lastName = lastName;
		this.salary = salary;
		this.address = address;
	}

	public int getId()
	{
		return id;
	}

	public void setId(int id)
	{
		this.id = id;
	}

	public String getFirstName()
	{
		return firstName;
	}

	public void setFirstName(String firstName)
	{
		this.firstName = firstName;
	}

	public String getLastName()
	{
		return lastName;
	}

	public void setLastName(String lastName)
	{
		this.lastName = lastName;
	}

	public int getSalary()
	{
		return salary;
	}

	public void setSalary(int salary)
	{
		this.salary = salary;
	}

	public Address getAddress()
	{
		return address;
	}

	public void setAddress(Address address)
	{
		this.address = address;
	}
}

Address.java

package com.jiangge.hblearn;

/**
 * @author shijiangge
 * @version 2014-7-4 上午11:05:39
 *
 */
public class Address
{
	private int id;
	private String street;
	private String city;
	private String state;
	private String zipcode;

	public Address()
	{
	}

	public Address(String street, String city, String state, String zipcode)
	{
		this.street = street;
		this.city = city;
		this.state = state;
		this.zipcode = zipcode;
	}

	public int getId()
	{
		return id;
	}

	public void setId(int id)
	{
		this.id = id;
	}

	public String getStreet()
	{
		return street;
	}

	public void setStreet(String street)
	{
		this.street = street;
	}

	public String getCity()
	{
		return city;
	}

	public void setCity(String city)
	{
		this.city = city;
	}

	public String getState()
	{
		return state;
	}

	public void setState(String state)
	{
		this.state = state;
	}

	public String getZipcode()
	{
		return zipcode;
	}

	public void setZipcode(String zipcode)
	{
		this.zipcode = zipcode;
	}
}

在MySQL中创建表:

create table EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   salary     INT  default NULL,
   address    INT NOT NULL,
   PRIMARY KEY (id)
);
create table ADDRESS (
   id INT NOT NULL auto_increment,
   street_name VARCHAR(40) default NULL,
   city_name VARCHAR(40) default NULL,
   state_name VARCHAR(40) default NULL,
   zipcode VARCHAR(10) default NULL,
   PRIMARY KEY (id)
);

三、创建对象-关系映射文件(Employee.hbm.xml)

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<!--
Hibernate Many-to-One 关联关系:
很多员工可以对应一个地址。

初级的程序员手写 Employee.hbm.xml 映射文件,而高级程序员使用XDoclet, Middlegen and AndroMDA这些技术,自动生成映射文件。

meta 标签是可选的,用来描述类。

Hibernate的主键生成策略:
【identity】采用数据库提供的主键生成机制。如DB2、SQL Server、MySQL 中的主键生成机制。
【native】由 Hibernate 根据使用的数据库自行判断采用 identity、hilo、sequence 其中一种作为主键生成方式。
 -->
<hibernate-mapping>
	<class name="com.jiangge.hblearn.Employee" table="EMPLOYEE">
		<meta attribute="class-description">
			This class contains the employee detail.
		</meta>
		<id name="id" type="int" column="id">
			<generator class="native" />
		</id>
		<property name="firstName" column="first_name" type="string" />
		<property name="lastName" column="last_name" type="string" />
		<property name="salary" column="salary" type="int" />
		<many-to-one name="address" column="address" class="com.jiangge.hblearn.Address" not-null="true" />
	</class>

	<class name="com.jiangge.hblearn.Address" table="ADDRESS">
		<meta attribute="class-description">
			This class contains the address detail.
		</meta>
		<id name="id" type="int" column="id">
			<generator class="native" />
		</id>
		<property name="street" column="street_name" type="string" />
		<property name="city" column="city_name" type="string" />
		<property name="state" column="state_name" type="string" />
		<property name="zipcode" column="zipcode" type="string" />
	</class>

</hibernate-mapping>

四、通过Hibernate API编写访问数据库的代码

package test;

import java.util.*;

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

import com.jiangge.hblearn.Address;
import com.jiangge.hblearn.Employee;

/**
 * 测试类:CRUD操作
 * @author jiangge
 *
 */
public class ManageEmployee
{
	private static SessionFactory factory;

	public static void main(String[] args)
	{
		try
		{
			factory = new Configuration().configure().buildSessionFactory();
		}
		catch (Throwable ex)
		{
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		}
		ManageEmployee ME = new ManageEmployee();

		/* Let us have one address object */
		Address address = ME.addAddress("Kondapur", "Hyderabad", "AP", "532");

		/* Add employee records in the database */
		Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, address); //("Manoj", "Kumar", 4000, address);

		/* Add another employee record in the database */
		Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, address);//("Dilip", "Kumar", 3000, address);

		/* List down all the employees */
		ME.listEmployees();

		/* Update employee's salary records */
		ME.updateEmployee(empID1, 5000);

		/* Delete an employee from the database */
		ME.deleteEmployee(empID2);

		/* List down all the employees */
		ME.listEmployees();

	}

	/* Method to add an address record in the database */
	public Address addAddress(String street, String city, String state, String zipcode)
	{
		Session session = factory.openSession();
		Transaction tx = null;
		Integer addressID = null;
		Address address = null;
		try
		{
			tx = session.beginTransaction();
			address = new Address(street, city, state, zipcode);
			addressID = (Integer) session.save(address);
			tx.commit();
		}
		catch (HibernateException e)
		{
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		}
		finally
		{
			session.close();
		}
		return address;
	}

	/* Method to add an employee record in the database */
	public Integer addEmployee(String fname, String lname, int salary,
			Address address)
	{
		Session session = factory.openSession();
		Transaction tx = null;
		Integer employeeID = null;
		try
		{
			tx = session.beginTransaction();
			Employee employee = new Employee(fname, lname, salary, address);
			employeeID = (Integer) session.save(employee);
			tx.commit();
		}
		catch (HibernateException e)
		{
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		}
		finally
		{
			session.close();
		}
		return employeeID;
	}

	/* Method to list all the employees detail */
	public void listEmployees()
	{
		Session session = factory.openSession();
		Transaction tx = null;
		try
		{
			tx = session.beginTransaction();
			List employees = session.createQuery("FROM Employee").list();
			for (Iterator iterator = employees.iterator(); iterator.hasNext();)
			{
				Employee employee = (Employee) iterator.next();
				System.out.print("First Name: " + employee.getFirstName());
				System.out.print("  Last Name: " + employee.getLastName());
				System.out.println("  Salary: " + employee.getSalary());
				Address add = employee.getAddress();
				System.out.println("Address ");
				System.out.println("\tStreet: " + add.getStreet());
				System.out.println("\tCity: " + add.getCity());
				System.out.println("\tState: " + add.getState());
				System.out.println("\tZipcode: " + add.getZipcode());
			}
			tx.commit();
		}
		catch (HibernateException e)
		{
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		}
		finally
		{
			session.close();
		}
	}

	/* Method to update salary for an employee */
	public void updateEmployee(Integer EmployeeID, int salary)
	{
		Session session = factory.openSession();
		Transaction tx = null;
		try
		{
			tx = session.beginTransaction();
			Employee employee = (Employee) session.get(Employee.class,
					EmployeeID);
			employee.setSalary(salary);
			session.update(employee);
			tx.commit();
		}
		catch (HibernateException e)
		{
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		}
		finally
		{
			session.close();
		}
	}

	/* Method to delete an employee from the records */
	public void deleteEmployee(Integer EmployeeID)
	{
		Session session = factory.openSession();
		Transaction tx = null;
		try
		{
			tx = session.beginTransaction();
			Employee employee = (Employee) session.get(Employee.class, EmployeeID);
			session.delete(employee);
			tx.commit();
		}
		catch (HibernateException e)
		{
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		}
		finally
		{
			session.close();
		}
	}
}

五、运行结果:

mysql>  select * from EMPLOYEE;
+----+------------+-----------+--------+---------+
| id | first_name | last_name | salary | address |
+----+------------+-----------+--------+---------+
|  1 | Manoj      | Kumar     |   5000 |       1 |
+----+------------+-----------+--------+---------+
1 row in set

mysql> select * from ADDRESS;
+----+-------------+-----------+------------+---------+
| id | street_name | city_name | state_name | zipcode |
+----+-------------+-----------+------------+---------+
|  1 | Kondapur    | Hyderabad | AP         | 532     |
+----+-------------+-----------+------------+---------+
1 row in set

mysql> 

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into ADDRESS (street_name, city_name, state_name, zipcode) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE (first_name, last_name, salary, address) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE (first_name, last_name, salary, address) values (?, ?, ?, ?)
Hibernate: select employee0_.id as id0_, employee0_.first_name as first2_0_, employee0_.last_name as last3_0_, employee0_.salary as salary0_, employee0_.address as address0_ from EMPLOYEE employee0_
First Name: Manoj  Last Name: Kumar  Salary: 4000
Address
Hibernate: select address0_.id as id1_0_, address0_.street_name as street2_1_0_, address0_.city_name as city3_1_0_, address0_.state_name as state4_1_0_, address0_.zipcode as zipcode1_0_ from ADDRESS address0_ where address0_.id=?
	Street: Kondapur
	City: Hyderabad
	State: AP
	Zipcode: 532
First Name: Dilip  Last Name: Kumar  Salary: 3000
Address
	Street: Kondapur
	City: Hyderabad
	State: AP
	Zipcode: 532
Hibernate: select employee0_.id as id0_0_, employee0_.first_name as first2_0_0_, employee0_.last_name as last3_0_0_, employee0_.salary as salary0_0_, employee0_.address as address0_0_ from EMPLOYEE employee0_ where employee0_.id=?
Hibernate: update EMPLOYEE set first_name=?, last_name=?, salary=?, address=? where id=?
Hibernate: select employee0_.id as id0_0_, employee0_.first_name as first2_0_0_, employee0_.last_name as last3_0_0_, employee0_.salary as salary0_0_, employee0_.address as address0_0_ from EMPLOYEE employee0_ where employee0_.id=?
Hibernate: delete from EMPLOYEE where id=?
Hibernate: select employee0_.id as id0_, employee0_.first_name as first2_0_, employee0_.last_name as last3_0_, employee0_.salary as salary0_, employee0_.address as address0_ from EMPLOYEE employee0_
First Name: Manoj  Last Name: Kumar  Salary: 5000
Address
Hibernate: select address0_.id as id1_0_, address0_.street_name as street2_1_0_, address0_.city_name as city3_1_0_, address0_.state_name as state4_1_0_, address0_.zipcode as zipcode1_0_ from ADDRESS address0_ where address0_.id=?
	Street: Kondapur
	City: Hyderabad
	State: AP
	Zipcode: 532

参考文献:

http://www.tutorialspoint.com/hibernate/hibernate_many_to_one_mapping.htm

Hibernate ManyToOne Mappings 多对一关联映射,布布扣,bubuko.com

时间: 2024-12-28 12:53:35

Hibernate ManyToOne Mappings 多对一关联映射的相关文章

Hibernate之实现多对多关联映射关系

直接以老师与学生的关系为例.在多对多关联关系中,其中一方都可通过Set保留另一方的所有信息,这样的关联是双向关联.在多对多关联关系中,也只能是双向关联.老师和学生分别对应一张表,通过一张有双方id的中间表来维护多对多的关联. 实体类 package test.hibernate.hbmManyToMany; import java.util.HashSet; import java.util.Set; public class Teacher { private Integer id; priv

Hibernate框架单向多对一关联映射关系

建立多对一的单向关联关系    Emp.java            private Integer empNo //员工编号            private String empName //员工姓名            //private Integer deptNo;  //部门编号            private Dept dept;    //所属部门    Dept.java            private Byte deptNo;              

6.Hibernate单向的多对一 关联映射

1.创建如下项目结构 2.在项目的src下创建hibernate.cfg.xml主配置文件 1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.

一口一口吃掉Hibernate(六)——多对多关联映射

今天来说说hibernate中的多对多关联映射,多对多关联映射涉及到单向映射和双向映射2种. 首先举个多对多关联例子:用户User和角色Role,一个用户可以属于多个角色,一个角色可以有多个用户.这就是典型的多对多关联的例子.而单向关联映射则是只能由A端去操作B端,B端不能操作A端的数据.而双向关联映射则是A,B两端都可以操作另一端的数据. 先说单向关联映射,实体类如下: <span style="font-size:18px">/** * 学生类 * @author Lo

【SSH系列】Hibernate映射 -- 多对多关联映射

     映射原理 在数据库学习阶段,我们知道,如果实体和实体之间的关系是多对多,那么我们就抽出来第三张表,第一张表和第二张表的主键作为第三表的联合主键,结合我们的hibernate,多对多关联,无论是单向关联还是双向关联都是通过第三张表,将两个表中的主键放到第三张表中做一个关联,用第三张表来解决可能造成的数据冗余问题.今天这篇博文小编来简单的介绍一下hibernate中的多对多关联映射. 在某些系统中,一个用户可以有多个角色,一个角色也可以有多个用户,so,她们之间的关系就是多对多,多对多关联

hibernate多对一关联映射

hibernate多对一关联映射: 实体类 (POJO) public class Student{ private int stuId; private String stuNum; private String stuName; private ClassRoom cr; } public class ClassRoom{ private int claId; private String claName; } 映射文件 <class name=" Student" tabl

hibernate之关于使用连接表实现多对一关联映射

[Hibernate]之关于使用连接表实现多对一关联映射 在我们项目使用中采用中间表最多的一般就是多对一,或者是多对多,当然一对一使用中间表也是可以的,但是这种几率通常少之又少!所以这里重点介绍多对一和一对多的采用中间表进行关联映射! 依然采用Group和Person来描述这个逻辑! Annotations配置 @Entity @Table(name="t_group") publicclass Group {     private Integer id;     private S

【SSH进阶之路】Hibernate映射——多对多关联映射(八)

上篇博文[SSH进阶之路]Hibernate映射--一对多关联映射(七),我们介绍了一对多关联映射,它是多对多关联映射的基础. 多对多映射是现实生活中最常见的映射,也是最容易理解的映射.废话少说,直接开始. 映射原理 不论是单向关联还是双向关联都是通过第三张表,将两个表中的主键放到第三张做一个关联.用第三张表来解决可能会造成数据冗余的问题. 举例 一个用户(User)对多个角色(Role),一个角色对多个用户. 分类 单向的多对多关联映射(单向User--->Role) 对象模型 关系模型 实例

016 多对多关联映射 单向(many-to-many)

一般的设计中,多对多关联映射,需要一个中间表 Hibernate会自动生成中间表 Hibernate使用many-to-many标签来表示多对多的关联 多对多的关联映射,在实体类中,跟一对多一样,也是用集合来表示的. 实例场景: 用户与他的角色(一个用户拥有多个角色,一个角色还可以属于多个用户) Role实体类: public class Role { private int id; private String name; public int getId() { return id; } p