开发手册 欢迎您!
软件开发者资料库

JPA - Entity Relationships

JPA Entity Relationships - 使用这个初学者教程,简单易学地学习JPA,该教程包含从简介,架构,ORM组件,安装,实体管理器,JPQL,高级映射,实体关系和标准API开始的基础知识到高级知识。

本章将向您介绍实体之间的关系.通常,关系在数据库中的表之间更有效.这里实体类被视为关系表(JPA的概念),因此实体类之间的关系如下:

  • @ManyToOne关系

  • @OneToMany Relation

  • @OneToOne Relation

  • @ManyToMany Relation

@ManyToOne Relation

实体之间的多对一关系:其中一个实体(一列或一组列)被引用另一个包含唯一值的实体(列或列集).在关系数据库中,这些关系适用于表之间的外键/主键.

让我们考虑一下Employee和Department实体之间关系的一个例子.以单向方式,即从员工到部门,多对一关系是适用的.这意味着员工的每条记录都包含一个部门ID,该部门ID应该是Department表中的主键.在Employee表中,Department id是外键.

该图解释了Many-To-One关系,如下所示:

@ ManyToOne Relation

在eclipse IDE中创建一个名为 JPA_Eclipselink_MTO 的JPA项目.该项目的所有模块如下所示:

创建实体

按照上面给出的图表创建实体.在'src'包下创建名为'com.tutorialspoin.eclipselink.entity'的包.在给定的包下创建一个名为 Department.java 的类.类Department实体如下所示:

package com.it1352.eclipselink.entity; import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entitypublic 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.java的Employee实体类 'com.it1352.eclipselink.entity'包下. Employee实体类如下所示:

package com.it1352.eclipselink.entity; import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.ManyToOne;@Entitypublic 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

需要配置Persistence.xml文件数据库和实体类的注册.

创建JPA项目时,eclipse IDE将创建Persitence.xml.配置详细信息是用户规范. persistence.xml文件如下所示:

            com.IT屋.eclipselink.entity.Employee      com.IT屋.eclipselink.entity.Department                                                                                 

服务类

此模块包含实现关系的服务类部分使用属性初始化.在名为'com.it1352.eclipselink.service''src'包下创建一个包.在给定包下创建名为 ManyToOne.java 的DAO类. DAO类如下所示:

package com.it1352eclipselink.service; import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;import com.IT屋.eclipselink.entity.Department;import com.IT屋.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;IdName101Development


在MySQL界面中传递以下查询以及 Employee

Select * from employee;Eid Deg                 Ename        SalaryDepartment_Id102 Technical WriterSatish        45000101103 Technical WriterKrishna        45000101104 Technical WriterMasthan Wali50000101


在上表中,Deparment_Id是Department表中的外键(引用字段).

@OneToMany Relation

在此关系中,一个实体的每一行都引用其他实体中的许多子记录.重要的是,儿童记录不能有多个父母.在表A和表B之间的一对多关系中,表A中的每一行都链接到表B中的0,1或多行.

让我们考虑上面的例子.如果员工部门采用反向单向方式,则关系为多对一关系.在eclipse IDE中创建一个名为 JPA_Eclipselink_OTM 的JPA项目.该项目的所有模块如下所示:

创建实体

按照上面给出的图表创建实体.在'src'包下创建名为'com.tutorialspoin.eclipselink.entity'的包.在给定的包下创建一个名为 Department.java 的类.类Department实体如下所示:

package com.it1352.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;@Entitypublic 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.it1352.eclipselink.entity'包下. Employee实体类如下所示:

package com.it1352.eclipselink.entity; import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entitypublic 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

Persistence.xml将在创建JPA项目时由eclipse IDE创建.配置详细信息是用户规范. persistence.xml文件如下所示:

         com.IT屋.eclipselink.entity.Employee      com.IT屋.eclipselink.entity.Department                                                                                 


服务类

此模块包含服务类,它使用属性初始化实现关系部分.在名为'com.it1352.eclipselink.service''src'包下创建一个包.名为 OneToMany.java 的DAO类是在给定包下创建的. DAO类如下所示:

package com.it1352eclipselink.service; import java.util.List;import java.util.ArrayList;import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;import com.IT屋.eclipselink.entity.Department;import com.IT屋.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 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_IdEmployee_Eid254        251254        252254        253


在上表中,deparment_id和employee_id字段是来自部门和员工表的外键(引用字段).

在MySQL界面中传递以下查询,并以表格格式显示部门表的结果显示为在查询中跟随:

Select * from department;IdName254Development


在MySQL界面中传递以下查询,并在表格中传递employee表的结果格式在查询中显示如下:

Select * from employee;EidDeg                Ename       Salary251Technical WriterSatish       45000252Technical WriterKrishna       45000253Technical WriterMasthanvali    50000

@OneToOne关系

在一对一关系中,一个项目只能属于另一个项目.这意味着一个实体的每一行被称为另一个实体的一行且仅一行.

让我们考虑上面的例子. 员工部门以反向单向方式,关系是一对一关系.这意味着每个员工只属于一个部门.在eclipse IDE中创建一个名为 JPA_Eclipselink_OTO 的JPA项目.该项目的所有模块如下所示:

创建实体

按照上面给出的图表创建实体.在'src'包下创建名为'com.tutorialspoin.eclipselink.entity'的包.在给定的包下创建一个名为 Department.java 的类.类Department实体显示如下:

package com.it1352.eclipselink.entity; import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entitypublic 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.it1352.eclipselink.entity'包下. Employee实体类如下所示:

package com.it1352.eclipselink.entity; import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.OneToOne;@Entitypublic 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

Persistence.xml将由在创建JPA项目时使用eclipse IDE.配置详细信息是用户规范. persistence.xml文件如下所示:

            com.IT屋.eclipselink.entity.Employee      com.IT屋.eclipselink.entity.Department                                                                              


服务类

此模块包含服务类,它使用属性初始化实现关系部分.在名为'com.it1352.eclipselink.service''src'包下创建一个包.在给定包下创建名为 OneToOne.java 的DAO类. DAO类如下所示:

package com.it1352.eclipselink.service;import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;import com.it1352.eclipselink.entity.Department;import com.it1352.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 表的结果在查询中显示如下:

 从部门选择*  Id名称 301开发


在MySQL界面中传递以下查询,表格格式的 employee 表的结果在查询中显示如下:

Select * from departmentIdName301Development


@ManyToMany Relation

多对多关系是指来自一个实体的一行或多行与其他实体中的一行.

让我们考虑一下Class和Teacher实体之间关系的一个例子.以双向方式,班级和教师都有多对一的关系.这意味着Class的每个记录都由Teacher set(teacher id)引用,它应该是Teacher表中的主键并存储在Teacher_Class表中,反之亦然.这里,Teachers_Class表包含两个外键字段.在eclipse IDE中创建一个名为 JPA_Eclipselink_MTM 的JPA项目.该项目的所有模块如下所示:

@ ManyToOne Relation

创建实体

按照上面给出的图表创建实体.在'src'包下创建名为'com.tutorialspoin.eclipselink.entity'的包.在给定的包下创建一个名为 Clas.java 的类.类Department实体如下所示:

package com.it1352.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;@Entitypublic 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.it1352.eclipselink.entity'包下. Employee实体类如下所示:

package com.it1352.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;@Entitypublic 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

Persistence.xml将由在创建JPA项目的同时eclipse IDE.配置详细信息是用户规范. persistence.xml文件如下所示:

            com.IT屋.eclipselink.entity.Employee      com.IT屋.eclipselink.entity.Department                                                            


服务类

此模块包含服务类,它实现了使用属性初始化的关系部分.在名为'com.it1352.eclipselink.service''src'包下创建一个包.在给定包下创建名为 ManyToMany.java 的DAO类. DAO类如下所示:

package com.it1352.eclipselink.service; import java.util.HashSet;import java.util.Set;import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;import com.IT屋.eclipselink.entity.Clas;import com.IT屋.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 classSet1 = new HashSet();   classSet1.add(clas1);   classSet1.add(clas2);   classSet1.add(clas3);   //Create Clas Set2   Set classSet2 = new HashSet();   classSet2.add(clas3);   classSet2.add(clas1);   classSet2.add(clas2);   //Create Clas Set3   Set 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 _tidClasset_cid354        351355        351356        351354        352355        352356        352354        353355        353356        353


在上表中,teacher_tid是来自教师表的外键,而classet_cid是类表中的外键.因此,不同的教师被分配到不同的班级.

在MySQL界面中传递以下查询,表格格式的教师表结果如下所示:

Select * from teacher;TidSubject    Tname354Java    Satish355Adv Java    Krishna356DB2         Masthanvali


在MySQL界面中传递以下查询,表格格式的 clas 表的结果在查询中显示如下:

Select * from clas;cidCname3511st3522nd3533rd