JPA - 实体关系
-
简述
本章将带您了解实体之间的关系。通常,数据库中表之间的关系更有效。这里将实体类视为关系表(JPA的概念),因此实体类之间的关系如下:- @ManyToOne 关系
- @OneToMany 关系
- @OneToOne 关系
- @ManyToMany 关系
-
@ManyToOne 关系
实体之间的多对一关系:其中一个实体(列或列集)被另一个包含唯一值的实体(列或列集)引用。在关系数据库中,这些关系可以通过在表之间使用外键/主键来应用。让我们考虑 Employee 和 Department 实体之间的关系示例。在单向方式中,即从员工到部门,多对一关系适用。这意味着员工的每条记录都包含一个部门 ID,它应该是部门表中的主键。在 Employee 表中,Department id 是外键。该图解释了多对一关系如下:在 Eclipse IDE 中创建一个名为的 JPA 项目 JPA_Eclipselink_MTO. 本项目所有模块如下图所示:创建实体
按照上面给出的图表创建实体。创建一个名为的包‘com.tutorialspoin.eclipselink.entity’ 在下面 ‘src’包裹。创建一个名为的类Department.java在给定的包下。类Department实体如下图:package com.jc2182.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Department { @Id @GeneratedValue( strategy=GenerationType.AUTO ) 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 deptName ){ this.name = deptName; } }
在此关系中创建第二个实体 - 名为 Employee 实体类 Employee.java 在下面 ‘com.jc2182.eclipselink.entity’包裹。Employee 实体类如下所示:package com.jc2182.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity public class Employee{ @Id @GeneratedValue( strategy= GenerationType.AUTO ) private int eid; private String ename; private double salary; private String deg; @ManyToOne private Department department; public Employee(int eid, String ename, double salary, String deg) { super( ); this.eid = eid; this.ename = ename; this.salary = salary; this.deg = deg; } public Employee( ) { super(); } public int getEid( ) { return eid; } public void setEid(int eid) { this.eid = eid; } public String getEname( ) { return ename; } public void setEname(String ename) { this.ename = ename; } public double getSalary( ) { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDeg( ) { return deg; } public void setDeg(String deg) { this.deg = deg; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } }
持久化文件
需要 Persistence.xml 文件来配置数据库和实体类的注册。Persiteence.xml 将在创建 JPA 项目时由 Eclipse IDE 创建。配置详细信息是用户规范。persistence.xml 文件如下所示:<?xml version="1.0" encoding = "UTF-8"?> <persistence version = "2.0" xmlns = "http://java.sun.com/xml/ns/persistence" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name = "Eclipselink_JPA" transaction-type = "RESOURCE_LOCAL"> <class>com.jc2182.eclipselink.entity.Employee</class> <class>com.jc2182.eclipselink.entity.Department</class> <properties> <property name = "javax.persistence.jdbc.url" value = "jdbc:mysql://localhost:3306/jpadb"/> <property name = "javax.persistence.jdbc.user" value = "root"/> <property name = "javax.persistence.jdbc.password" value="root"/> <property name = "javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name = "eclipselink.logging.level" value = "FINE"/> <property name = "eclipselink.ddl-generation" value = "create-tables"/> </properties> </persistence-unit> </persistence>
服务类
该模块包含服务类,它使用属性初始化实现关系部分。在下面创建一个包‘src’ 包命名 ‘com.jc2182.eclipselink.service’. 名为的 DAO 类ManyToOne.java在给定的包下创建。DAO类如下所示:package com.jc2182eclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.jc2182.eclipselink.entity.Department; import com.jc2182.eclipselink.entity.Employee; public class ManyToOne { public static void main( String[ ] args ) { EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory.createEntityManager( ); entitymanager.getTransaction( ).begin( ); //Create Department Entity Department department = new Department(); department.setName("Development"); //Store Department entitymanager.persist(department); //Create Employee1 Entity Employee employee1 = new Employee(); employee1.setEname("Satish"); employee1.setSalary(45000.0); employee1.setDeg("Technical Writer"); employee1.setDepartment(department); //Create Employee2 Entity Employee employee2 = new Employee(); employee2.setEname("Krishna"); employee2.setSalary(45000.0); employee2.setDeg("Technical Writer"); employee2.setDepartment(department); //Create Employee3 Entity Employee employee3 = new Employee(); employee3.setEname("Masthanvali"); employee3.setSalary(50000.0); employee3.setDeg("Technical Writer"); employee3.setDepartment(department); //Store Employees entitymanager.persist(employee1); entitymanager.persist(employee2); entitymanager.persist(employee3); entitymanager.getTransaction().commit(); entitymanager.close(); emfactory.close(); } }
编译并执行上述程序后,您将在 Eclipse IDE 的控制台面板中收到通知。对于输出,请检查 MySQL 工作台。在此示例中,创建了两个表。在 MySQL 接口中传递以下查询和结果 Department 查询中以表格形式显示的表格如下:Select * from department; Id Name 101 Development
在 MySQL 接口中传递以下查询和结果 Employee 查询中以表格形式显示的表格如下:Select * from employee; Eid Deg Ename Salary Department_Id 102 Technical Writer Satish 45000 101 103 Technical Writer Krishna 45000 101 104 Technical Writer Masthan Wali 50000 101
在上表中,Deparment_Id 是 Department 表中的外键(引用字段)。 -
@OneToMany 关系
在这种关系中,一个实体的每一行都引用了另一个实体中的许多子记录。重要的是子记录不能有多个父记录。在表 A 和表 B 之间的一对多关系中,表 A 中的每一行都链接到表 B 中的 0、1 或许多行。让我们考虑上面的例子。如果Employee 和 Department是反向单向方式,关系是多对一关系。在 Eclipse IDE 中创建一个名为的 JPA 项目JPA_Eclipselink_OTM. 本项目所有模块如下图所示:创建实体
按照上面给出的图表创建实体。创建一个名为的包‘com.tutorialspoin.eclipselink.entity’ 在下面 ‘src’包裹。创建一个名为的类Department.java在给定的包下。类Department实体如下图:package com.jc2182.eclipselink.entity; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class Department { @Id @GeneratedValue( strategy=GenerationType.AUTO ) private int id; private String name; @OneToMany( targetEntity=Employee.class ) private List employeelist; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName( ) { return name; } public void setName( String deptName ) { this.name = deptName; } public List getEmployeelist() { return employeelist; } public void setEmployeelist(List employeelist) { this.employeelist = employeelist; } }
在此关系中创建第二个实体 -Employee 实体类,命名为 Employee.java 在下面 ‘com.jc2182.eclipselink.entity’包裹。Employee 实体类如下所示:package com.jc2182.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Employee { @Id @GeneratedValue( strategy= GenerationType.AUTO ) private int eid; private String ename; private double salary; private String deg; public Employee(int eid, String ename, double salary, String deg) { super( ); this.eid = eid; this.ename = ename; this.salary = salary; this.deg = deg; } public Employee( ) { super(); } public int getEid( ) { return eid; } public void setEid(int eid) { this.eid = eid; } public String getEname( ) { return ename; } public void setEname(String ename) { this.ename = ename; } public double getSalary( ) { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDeg( ) { return deg; } public void setDeg(String deg) { this.deg = deg; } }
持久化文件
Persistence.xml 将在创建 JPA 项目时由 Eclipse IDE 创建。配置详细信息是用户规范。persistence.xml 文件如下所示:<?xml version = "1.0" encoding = "UTF-8"?> <persistence version = "2.0" xmlns = "http://java.sun.com/xml/ns/persistence" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name = "Eclipselink_JPA" transaction-type = "RESOURCE_LOCAL"> <class>com.jc2182.eclipselink.entity.Employee</class> <class>com.jc2182.eclipselink.entity.Department</class> <properties> <property name = "javax.persistence.jdbc.url" value = "jdbc:mysql://localhost:3306/jpadb"/> <property name = "javax.persistence.jdbc.user" value = "root"/> <property name = "javax.persistence.jdbc.password" value = "root"/> <property name = "javax.persistence.jdbc.driver" value = "com.mysql.jdbc.Driver"/> <property name = "eclipselink.logging.level" value = "FINE"/> <property name = "eclipselink.ddl-generation" value = "create-tables"/> </properties> </persistence-unit> </persistence>
服务类
该模块包含服务类,它使用属性初始化实现关系部分。在下面创建一个包‘src’ 包命名 ‘com.jc2182.eclipselink.service’. 名为的 DAO 类OneToMany.java在给定的包下创建。DAO类如下所示:package com.jc2182eclipselink.service; import java.util.List; import java.util.ArrayList; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.jc2182.eclipselink.entity.Department; import com.jc2182.eclipselink.entity.Employee; public class OneToMany { public static void main(String[] args) { EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory.createEntityManager( ); entitymanager.getTransaction( ).begin( ); //Create Employee1 Entity Employee employee1 = new Employee(); employee1.setEname("Satish"); employee1.setSalary(45000.0); employee1.setDeg("Technical Writer"); //Create Employee2 Entity Employee employee2 = new Employee(); employee2.setEname("Krishna"); employee2.setSalary(45000.0); employee2.setDeg("Technical Writer"); //Create Employee3 Entity Employee employee3 = new Employee(); employee3.setEname("Masthanvali"); employee3.setSalary(50000.0); employee3.setDeg("Technical Writer"); //Store Employee entitymanager.persist(employee1); entitymanager.persist(employee2); entitymanager.persist(employee3); //Create Employeelist List<Employee> emplist = new ArrayList(); emplist.add(employee1); emplist.add(employee2); emplist.add(employee3); //Create Department Entity Department department = new Department(); department.setName("Development"); department.setEmployeelist(emplist); //Store Department entitymanager.persist(department); entitymanager.getTransaction().commit(); entitymanager.close(); emfactory.close(); } }
编译并执行上述程序后,您将在 Eclipse IDE 的控制台面板中收到通知。对于输出检查 MySQL 工作台如下。在这个项目中创建了三个表。在 MySQL 接口中传递以下查询和结果 department_employee 查询中以表格形式显示的表格如下:Select * from department_Id; Department_Id Employee_Eid 254 251 254 252 254 253
在上表中,deparment_id 和employee_id 字段是来自department 和employee 表的外键(引用字段)。在MySQL界面中通过如下查询,查询中的部门表结果以表格形式显示如下:Select * from department; Id Name 254 Development
在MySQL界面中通过如下查询,查询表中employee表的结果如下图所示:Select * from employee; Eid Deg Ename Salary 251 Technical Writer Satish 45000 252 Technical Writer Krishna 45000 253 Technical Writer Masthanvali 50000
-
@OneToOne 关系
在一对一关系中,一项只能属于另一项。这意味着一个实体的每一行都被引用到另一个实体的一个且只有一行。让我们考虑上面的例子。 Employee 和 Department以反向单向方式,该关系是一对一关系。这意味着每个员工只属于一个部门。在 Eclipse IDE 中创建一个名为的 JPA 项目JPA_Eclipselink_OTO. 本项目所有模块如下图所示:创建实体
按照上面给出的图表创建实体。创建一个名为的包‘com.tutorialspoin.eclipselink.entity’ 在下面 ‘src’包裹。创建一个名为的类Department.java在给定的包下。类Department实体如下图:package com.jc2182.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Department { @Id @GeneratedValue( strategy=GenerationType.AUTO ) 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 deptName ) { this.name = deptName; } }
在此关系中创建第二个实体 -Employee 实体类,命名为 Employee.java 在下面 ‘com.jc2182.eclipselink.entity’包裹。Employee 实体类如下所示:package com.jc2182.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity public class Employee { @Id @GeneratedValue( strategy= GenerationType.AUTO ) private int eid; private String ename; private double salary; private String deg; @OneToOne private Department department; public Employee(int eid, String ename, double salary, String deg) { super( ); this.eid = eid; this.ename = ename; this.salary = salary; this.deg = deg; } public Employee( ) { super(); } public int getEid( ) { return eid; } public void setEid(int eid) { this.eid = eid; } public String getEname( ) { return ename; } public void setEname(String ename) { this.ename = ename; } public double getSalary( ) { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDeg( ) { return deg; } public void setDeg(String deg) { this.deg = deg; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } }
持久化文件
Persistence.xml 将在创建 JPA 项目时由 Eclipse IDE 创建。配置详细信息是用户规范。persistence.xml 文件如下所示:<?xml version = "1.0" encoding = "UTF-8"?> <persistence version = "2.0" xmlns = "http://java.sun.com/xml/ns/persistence" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name = "Eclipselink_JPA" transaction-type = "RESOURCE_LOCAL"> <class>com.jc2182.eclipselink.entity.Employee</class> <class>com.jc2182.eclipselink.entity.Department</class> <properties> <property name = "javax.persistence.jdbc.url" value = "jdbc:mysql://localhost:3306/jpadb"/> <property name = "javax.persistence.jdbc.user" value = "root"/> <property name = "javax.persistence.jdbc.password" value = "root"/> <property name = "javax.persistence.jdbc.driver" value = "com.mysql.jdbc.Driver"/> <property name = "eclipselink.logging.level" value = "FINE"/> <property name = "eclipselink.ddl-generation" value = "create-tables"/> </properties> </persistence-unit> </persistence>
服务类
该模块包含服务类,它使用属性初始化实现关系部分。在下面创建一个包‘src’ 包命名 ‘com.jc2182.eclipselink.service’. 名为的 DAO 类OneToOne.java在给定的包下创建。DAO类如下所示:package com.jc2182eclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.jc2182.eclipselink.entity.Department; import com.jc2182.eclipselink.entity.Employee; public class OneToOne { public static void main(String[] args) { EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory.createEntityManager( ); entitymanager.getTransaction( ).begin( ); //Create Department Entity Department department = new Department(); department.setName("Development"); //Store Department entitymanager.persist(department); //Create Employee Entity Employee employee = new Employee(); employee.setEname("Satish"); employee.setSalary(45000.0); employee.setDeg("Technical Writer"); employee.setDepartment(department); //Store Employee entitymanager.persist(employee); entitymanager.getTransaction().commit(); entitymanager.close(); emfactory.close(); } }
编译并执行上述程序后,您将在 Eclipse IDE 的控制台面板中收到通知。对于输出,请按如下方式检查 MySQL 工作台。在上面的示例中,创建了两个表。在 MySQL 接口中传递以下查询和结果 department 查询中以表格形式显示的表格如下:Select * from department Id Name 301 Development
在 MySQL 接口中传递以下查询和结果 employee 查询中以表格形式显示的表格如下:Select * from employee Eid Deg Ename Salary Department_id 302 Technical Writer Satish 45000 301
-
@ManyToMany 关系
多对多关系是指一个实体中的一行或多行与其他实体中的多行相关联。让我们考虑一个 Class 和 Teacher 实体之间关系的例子。在双向方式中,Class 和Teacher 都具有多对一的关系。这意味着 Class 的每条记录都由教师集(教师 ID)引用,教师集应该是 Teacher 表中的主键并存储在 Teacher_Class 表中,反之亦然。在这里,Teachers_Class 表包含两个外键字段。在 Eclipse IDE 中创建一个名为的 JPA 项目JPA_Eclipselink_MTM. 本项目所有模块如下图所示:创建实体
按照上面给出的图表创建实体。创建一个名为的包‘com.tutorialspoin.eclipselink.entity’ 在下面 ‘src’包裹。创建一个名为的类Clas.java在给定的包下。类Department实体如下图:package com.jc2182.eclipselink.entity; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; @Entity public class Clas { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private int cid; private String cname; @ManyToMany(targetEntity=Teacher.class) private Set teacherSet; public Clas(){ super(); } public Clas(int cid, String cname, Set teacherSet) { super(); this.cid = cid; this.cname = cname; this.teacherSet = teacherSet; } public int getCid(){ return cid; } public void setCid(int cid) { this.cid = cid; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public Set getTeacherSet() { return teacherSet; } public void setTeacherSet(Set teacherSet) { this.teacherSet = teacherSet; } }
在此关系中创建第二个实体 -Employee 实体类,命名为 Teacher.java 在下面 ‘com.jc2182.eclipselink.entity’包裹。Employee 实体类如下所示:package com.jc2182.eclipselink.entity; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; @Entity public class Teacher { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private int tid; private String tname; private String subject; @ManyToMany(targetEntity = Clas.class) private Set clasSet; public Teacher(){ super(); } public Teacher(int tid, String tname, String subject, Set clasSet) { super(); this.tid = tid; this.tname = tname; this.subject = subject; this.clasSet = clasSet; } public int getTid() { return tid; } public void setTid(int tid) { this.tid = tid; } public String getTname() { return tname; } public void setTname(String tname) { this.tname = tname; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public Set getClasSet() { return clasSet; } public void setClasSet(Set clasSet) { this.clasSet = clasSet; } }
持久化文件
Persistence.xml 将由 Eclipse IDE 在创建 JPA 项目时创建。配置详细信息是用户规范。persistence.xml 文件如下所示:<?xml version = "1.0" encoding = "UTF-8"?> <persistence version = "2.0" xmlns = "http://java.sun.com/xml/ns/persistence" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name = "Eclipselink_JPA" transaction-type = "RESOURCE_LOCAL"> <class>com.jc2182.eclipselink.entity.Employee</class> <class>com.jc2182.eclipselink.entity.Department</class> <properties> <property name = "javax.persistence.jdbc.url" value = "jdbc:mysql://localhost:3306/jpadb"/> <property name = "javax.persistence.jdbc.user" value = "root"/> <property name = "javax.persistence.jdbc.password" value = "root"/> <property name = "javax.persistence.jdbc.driver" value = "com.mysql.jdbc.Driver"/> <property name = "eclipselink.logging.level" value = "FINE"/> <property name = "eclipselink.ddl-generation" value = "create-tables"/> </properties> </persistence-unit> </persistence>
服务类
该模块包含服务类,它使用属性初始化实现关系部分。在下面创建一个包‘src’ 包命名 ‘com.jc2182.eclipselink.service’. 名为的 DAO 类ManyToMany.java在给定的包下创建。DAO类如下所示:package com.jc2182.eclipselink.service; import java.util.HashSet; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.jc2182.eclipselink.entity.Clas; import com.jc2182.eclipselink.entity.Teacher; public class ManyToMany { public static void main(String[] args) { EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory.createEntityManager( ); entitymanager.getTransaction( ).begin( ); //Create Clas Entity Clas clas1 = new Clas(0, "1st", null); Clas clas2 = new Clas(0, "2nd", null); Clas clas3 = new Clas(0, "3rd", null); //Store Clas entitymanager.persist(clas1); entitymanager.persist(clas2); entitymanager.persist(clas3); //Create Clas Set1 Set<Clas> classSet1 = new HashSet(); classSet1.add(clas1); classSet1.add(clas2); classSet1.add(clas3); //Create Clas Set2 Set<Clas> classSet2 = new HashSet(); classSet2.add(clas3); classSet2.add(clas1); classSet2.add(clas2); //Create Clas Set3 Set<Clas> classSet3 = new HashSet(); classSet3.add(clas2); classSet3.add(clas3); classSet3.add(clas1); //Create Teacher Entity Teacher teacher1 = new Teacher(0, "Satish","Java",classSet1); Teacher teacher2 = new Teacher(0, "Krishna","Adv Java",classSet2); Teacher teacher3 = new Teacher(0, "Masthanvali","DB2",classSet3); //Store Teacher entitymanager.persist(teacher1); entitymanager.persist(teacher2); entitymanager.persist(teacher3); entitymanager.getTransaction( ).commit( ); entitymanager.close( ); emfactory.close( ); } }
编译并执行上述程序后,您将在 Eclipse IDE 的控制台面板中收到通知。对于输出,请按如下方式检查 MySQL 工作台。在此示例项目中,创建了三个表。在 MySQL 接口中传递以下查询和结果 teacher_clas 查询中以表格形式显示的表格如下所示。Select * form teacher_clas; Teacher _tid Classet_cid 354 351 355 351 356 351 354 352 355 352 356 352 354 353 355 353 356 353
上表中teacher_tid是teacher表的外键,classet_cid是class表的外键。因此,不同的老师被分配到不同的班级。在MySQL界面中通过如下查询,查询中以表格形式显示teacher表的结果如下:Select * from teacher; Tid Subject Tname 354 Java Satish 355 Adv Java Krishna 356 DB2 Masthanvali
在 MySQL 接口中传递以下查询和结果 clas 查询中以表格形式显示的表格如下:Select * from clas; cid Cname 351 1st 352 2nd 353 3rd