Hibernate (11) - one to many association mapping

This blog series is summarized here: Hibernate summary

One to many association mapping

Source project file: Hibernate 4.3_

One to many association mapping

Class diagram:

Table relation:

1. Create model object

One end of create one

package com.wyx.hiber.model;

import java.util.Set;

public class Team
{

	private Integer tId;

	private String tName;

	private String loc;

	/**
	 * Specify a one to many relationship in the model
	 */
	private Set<Emp> set;

	public Set<Emp> getSet()
	{
		return set;
	}

	public void setSet(Set<Emp> set)
	{
		this.set = set;
	}

	public Integer gettId()
	{
		return tId;
	}

	public void settId(Integer tId)
	{
		this.tId = tId;
	}

	public String gettName()
	{
		return tName;
	}

	public void settName(String tName)
	{
		this.tName = tName;
	}

	public String getLoc()
	{
		return loc;
	}

	public void setLoc(String loc)
	{
		this.loc = loc;
	}

	@Override
	public String toString()
	{
		return "Team [tId=" + tId + ", tName=" + tName + ", loc=" + loc + "]";
	}

}

2. Configuration mapping file

Configure on one end

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 <hibernate-mapping package="com.wyx.hiber.model">
 	<class name="Team" table="t_team">
 		<id name="tId" column="t_id">
 			<generator class="native"></generator>
 		</id>
 		<property name="tName" column="t_name"></property>
 		<property name="loc"></property>
 		<!-- 
 			set Specify one to many relationship configuration
 			name: The property name of the collection in the model class at one end of
 		 -->
 		<set name="set">
 			<!-- 
 				key:Foreign key to be generated in a table on multiple ends
 				column: Foreign key name
 			 -->
 			<key column="t_id"></key>
 			<!-- 
 				one-to-many: Specify a class with multiple ends
 				class: Classes on the multiple end
 			 -->
 			<one-to-many class="Emp"/>
 		</set>
 	</class>
 </hibernate-mapping>

3. Test one to many

Preservation

public void testAdd()
{
	Session session = HibernateUtils.getSession();
	Transaction tx = session.beginTransaction();

	try
	{
		// Create staff
		Emp emp = new Emp();
		emp.setEname("Jordan");
		emp.setAddress("Chicago");
		emp.setBirthday(new Date());
		emp.setGender(1);
		// Employee retention
		session.save(emp);
		Emp emp1 = new Emp();
		emp1.setEname("Phil");
		emp1.setAddress("Chicago");
		emp1.setBirthday(new Date());
		emp1.setGender(1);
		session.save(emp1);
		// Team building
		Team team = new Team();
		team.settName("Bulls");
		team.setLoc("Chicago");

		// Add two employees to the collection
		Set<Emp> set = new HashSet<Emp>();
		set.add(emp);
		set.add(emp1);
		// Specify one to many relationship between team and staff
		team.setSet(set);
		// Save team
		session.save(team);
		tx.commit();
	} catch (Exception e)
	{
		e.printStackTrace();
		tx.rollback();
	} finally
	{
		HibernateUtils.closeResource(session);
	}
}


It can be seen from the output that when saving employees, the basic fields of employees are inserted first, the foreign key t ﹣ ID is empty, then the team is inserted, and finally the team foreign key t ﹣ ID of two employees is modified according to the generated team t ﹣ ID. The disadvantage is that if the foreign key in the employee table is not null, an error will be reported when inserting the employee.

You can also use cascading to save one to many relationships

query

public void testQuery()
{
	Session session = HibernateUtils.getSession();
	try
	{
		Team team = (Team) session.get(Team.class, 3);
		System.out.println(team);
		Set<Emp> set = team.getSet();
		for (Emp emp : set)
		{
			System.out.println(emp);
		}
	} catch (Exception e)
	{
		e.printStackTrace();
	} finally
	{
		HibernateUtils.closeResource(session);
	}
}

4. One to many two-way Association

One to many is defective. When saving, if the foreign key at the multiple end is not empty, one to many saving does not work.

(1) Create model

Create multiple ends

package com.wyx.hiber.model;

import java.util.Date;

public class Emp
{

	private Integer empNo;

	private String ename;

	private Date birthday;

	private Integer gender;

	private String address;
	/**
	 * Specify a many to one relationship
	 */
	private Team team;

	public Team getTeam()
	{
		return team;
	}

	public void setTeam(Team team)
	{
		this.team = team;
	}

	public Integer getEmpNo()
	{
		return empNo;
	}

	public void setEmpNo(Integer empNo)
	{
		this.empNo = empNo;
	}

	public String getEname()
	{
		return ename;
	}

	public void setEname(String ename)
	{
		this.ename = ename;
	}

	public Date getBirthday()
	{
		return birthday;
	}

	public void setBirthday(Date birthday)
	{
		this.birthday = birthday;
	}

	public Integer getGender()
	{
		return gender;
	}

	public void setGender(Integer gender)
	{
		this.gender = gender;
	}

	public String getAddress()
	{
		return address;
	}

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

	@Override
	public String toString()
	{
		return "Emp [empNo=" + empNo + ", ename=" + ename + ", birthday="
				+ birthday + ", gender=" + gender + ", address=" + address
				+ "]";
	}

}

(2) Modify configuration

Modify the configuration of multiple ends

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 <hibernate-mapping package="com.wyx.hiber.model">
 	<class name="Emp" table="t_emp">
 		<id name="empNo" column="emp_no">
 			<generator class="native"></generator>
 		</id>
 		<property name="ename"></property>
 		<property name="birthday"></property>
 		<property name="gender"></property>
 		<property name="address"></property>
 		<!-- 
 			Specify a many to one relationship:
 			Name: one end property name of one
 			column: the foreign key field to be generated in the table at multiple ends. Note that the foreign key has been configured in team.hbm.xml,
 			Now we need to configure this foreign key with the same name as the multiple foreign keys configured in team.hbm.xml,
 			Because these two configurations refer to the same column
 		 -->
 		<many-to-one name="team" column="t_id"></many-to-one>
 	</class>
 	
 </hibernate-mapping>

(3) Test one to many bidirectional

Preservation

To save one to many, you need to give the operation to the multiple end.

public void testAdd()
{
	Session session = HibernateUtils.getSession();
	Transaction tx = session.beginTransaction();

	try
	{

		// Team building
		Team team = new Team();
		team.settName("Bulls");
		team.setLoc("Chicago");
		// Save team
		session.save(team);

		// Create staff
		Emp emp = new Emp();
		emp.setEname("Jordan");
		emp.setAddress("Chicago");
		emp.setBirthday(new Date());
		emp.setGender(1);
		// Specify employee team relationship
		emp.setTeam(team);
		// Employee retention
		session.save(emp);
		Emp emp1 = new Emp();
		emp1.setEname("Phil");
		emp1.setAddress("Chicago");
		emp1.setBirthday(new Date());
		emp1.setGender(1);

		emp1.setTeam(team);
		session.save(emp1);
		tx.commit();
	} catch (Exception e)
	{
		e.printStackTrace();
		tx.rollback();
	} finally
	{
		HibernateUtils.closeResource(session);
	}
}


If there is a requirement that must be saved at one end, we can set inversion of control. We can operate at one end, and then save at multiple ends. The configuration needed is as follows:

Preservation:

public void testAdd1()
{
	Session session = HibernateUtils.getSession();
	Transaction tx = session.beginTransaction();

	try
	{

		// Team building
		Team team = new Team();
		team.settName("Bulls");
		team.setLoc("Chicago");

		// Create staff
		Emp emp = new Emp();
		emp.setEname("Jordan");
		emp.setAddress("Chicago");
		emp.setBirthday(new Date());
		emp.setGender(1);
		// Specify employee team relationship
		emp.setTeam(team);

		Emp emp1 = new Emp();
		emp1.setEname("Phil");
		emp1.setAddress("Chicago");
		emp1.setBirthday(new Date());
		emp1.setGender(1);
		emp1.setTeam(team);

		Set<Emp> set = new HashSet<Emp>();
		set.add(emp1);
		set.add(emp);
		team.setSet(set);

		// Save team
		session.save(team);

		tx.commit();
	} catch (Exception e)
	{
		e.printStackTrace();
		tx.rollback();
	} finally
	{
		HibernateUtils.closeResource(session);
	}
}

If there is any mistake, please correct it!

450 original articles published, 210 praised, 80000 visitors+
His message board follow

Tags: Session Hibernate xml Java

Posted on Wed, 29 Jan 2020 00:03:48 -0800 by nec9716