一对多关系指出一个实体的单个实例与另一个实体的多个实例相关联。 换句话说,一个表中的每个记录与另一个表中的多个记录相关联。
让我们看看如何通过XML映射文件在Hibernate中定义这种关系。
1.实体关系图
假设我们已经在数据库中创建了学生表和部门表,下面是MySQL数据库中学生表和部门表的实体关系图 。
2. Maven依赖
首先,在我们的maven项目中设置pom.xml文件。
确保我们将以下依赖项添加到我们的pom.xml文件中。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>
3.休眠配置设置
确保已配置hibernate.cfg.xml文件,并将其添加到类路径中的项目结构中。
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/sample_db</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="Student.hbm.xml" />
<mapping resource="Department.hbm.xml" />
</session-factory>
</hibernate-configuration>
4.实体类
在演示应用程序中,我们有两个实体,即学生和部门,为此,我们在数据库中有两个表。 因此,我们需要创建与这些表相对应的实体类。
学生.java
package com.jcombat.entity;
public class Student {
private String studentId;
private String firstName;
private String lastName;
private Department department;
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
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 Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
部门.java
package com.jcombat.entity;
import java.util.Set;
public class Department {
private String depId;
private String depName;
private Set<Student> students;
public String getDepId() {
return depId;
}
public void setDepId(String depId) {
this.depId = depId;
}
public String getDepName() {
return depName;
}
public void setDepName(String depName) {
this.depName = depName;
}
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
}
5. Hibernate Utility类
HibernateUtil.java
HibernateUtil.java
package com.jcombat.utility;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
@SuppressWarnings("deprecation")
private static SessionFactory buildSessionFactory() {
try {
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
6.休眠映射XML
为每个实体创建休眠映射文件。
Student.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!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.jcombat.entity">
<class name="Student" table="student">
<id name="studentId" column="ID">
<generator class="native" />
</id>
<property name="firstName" column="FNAME" />
<property name="lastName" column="LNAME" />
<many-to-one name="department" class="com.jcombat.entity.Department" fetch="select">
<column name="DEPT_ID" not-null="true" />
</many-to-one>
</class>
</hibernate-mapping>
Department.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!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.jcombat.entity">
<class name="Department" table="department">
<id name="depId" column="DEPT_ID">
<generator class="native" />
</id>
<property name="depName" column="DEP_NAME" />
<set name="students" table="student" inverse="true" cascade="save-update" lazy="true" fetch="select">
<key>
<column name="DEPT_ID" not-null="true" />
</key>
<one-to-many class="com.jcombat.entity.Student" />
</set>
</class>
</hibernate-mapping>
请注意,我们使用Set来映射与部门关联的学生。
集合映射中经常使用“ Cascade”关键字来自动管理集合的状态。 因此,如果有一组与特定部门相关联的Student,并且我们保留了Department对象的状态,则所有关联的子Student对象也会自动保留,从而节省了手动保留它们的人工。 我们当前的示例也会发生同样的情况。
7.最终项目结构
完成上述所有步骤后,请参考以下项目结构。
7.执行
我们快完成了。 剩下的唯一部分是从我们将执行应用程序的位置创建客户端类。 因此,让我们创建一个MainApp客户端类。
MainApp.java
package com.jcombat.hibernate;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.jcombat.entity.Department;
import com.jcombat.entity.Student;
import com.jcombat.utility.HibernateUtil;
public class MainApp {
public static void main(String[] args) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Department department = new Department();
department.setDepName("Electronics");
Student student1 = new Student();
student1.setFirstName("Abhimanyu");
student1.setLastName("Prasad");
student1.setDepartment(department);
Student student2 = new Student();
student2.setFirstName("Abhishek");
student2.setLastName("Kumar");
student2.setDepartment(department);
Set<Student> studSet = new HashSet<Student>();
studSet.add(student1);
studSet.add(student2);
department.setStudents(studSet);
session.save(department);
session.getTransaction().commit();
session.close();
}
}
右键单击该类,然后将其作为“ Java应用程序”运行。 我们看到以下条目已登录到IDE控制台。
Hibernate: insert into department (DEP_NAME) values (?)
Hibernate: insert into student (FNAME, LNAME, DEPT_ID) values (?, ?, ?)
Hibernate: insert into student (FNAME, LNAME, DEPT_ID) values (?, ?, ?)
验证数据库中的各个表是否有添加的条目。
- 下载源代码
翻译自: https://www.javacodegeeks.com/2015/12/one-many-xml-mapping-hibernate.html