Jpa-entity-relationships

提供:Dev Guides
移動先:案内検索

JPA-エンティティの関係

この章では、エンティティ間の関係について説明します。 一般に、データベース内のテーブル間の関係はより効果的です。 ここでは、エンティティクラスはリレーショナルテーブル(JPAの概念)として扱われるため、エンティティクラス間の関係は次のようになります。

  • @ManyToOneリレーション
  • @OneToMany関係
  • @OneToOneリレーション
  • @ManyToMany関係

@ManyToOneリレーション

エンティティ間の多対1の関係:1つのエンティティ(列または列のセット)が、一意の値を含む別のエンティティ(列または列のセット)で参照される場合。 リレーショナルデータベースでは、これらの関係は、テーブル間で外部キー/主キーを使用することで適用できます。

EmployeeエンティティとDepartmentエンティティ間の関係の例を考えてみましょう。 単方向、つまり従業員から部署へ、多対1の関係が適用されます。 つまり、従業員の各レコードには1つの部門IDが含まれており、これはDepartmentテーブルのプライマリキーでなければなりません。 ここで、Employeeテーブルでは、部門IDは外部キーです。

この図は、多対1の関係を次のように説明しています。

@ManyToOne Relation

*JPA_Eclipselink_MTO* という名前のEclipse IDEでJPAプロジェクトを作成します。 このプロジェクトのすべてのモジュールは次のとおりです。

エンティティの作成

上記の図に従ってエンティティを作成します。 ‘src’ パッケージの下に ’com.tutorialspoin.eclipselink.entity’ という名前のパッケージを作成します。 指定されたパッケージの下に Department.java という名前のクラスを作成します。 クラスDepartmentエンティティは次のように表示されます。

package com.finddevguides.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;
   }
}

このリレーションの2番目のエンティティを作成します- ‘com.finddevguides.eclipselink.entity’ パッケージの下に Employee.java という名前の従業員エンティティクラス。 Employeeエンティティクラスは次のように表示されます。

package com.finddevguides.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

データベースとエンティティクラスの登録を構成するには、Persistence.xmlファイルが必要です。

Persitence.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.finddevguides.eclipselink.entity.Employee</class>
      <class>com.finddevguides.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>

サービスクラス

このモジュールには、属性の初期化を使用してリレーショナル部分を実装するサービスクラスが含まれています。 ‘com.finddevguides.eclipselink.service’ という名前の ‘src’ パッケージの下にパッケージを作成します。 ManyToOne.java という名前のDAOクラスが、指定されたパッケージの下に作成されます。 DAOクラスは次のように表示されます。

package com.finddevguideseclipselink.service;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import com.finddevguides.eclipselink.entity.Department;
import com.finddevguides.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ワークベンチを確認してください。 この例では、2つのテーブルが作成されます。

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関係

この関係では、1つのエンティティの各行が、他のエンティティの多くの子レコードに参照されます。 重要なことは、子レコードが複数の親を持つことはできないということです。 テーブルAとテーブルBの1対多の関係では、テーブルAの各行は、テーブルBの0、1、または多くの行にリンクされます。

上記の例を考えてみましょう。* Employee と *Department が逆方向の場合、リレーションは多対1のリレーションです。 JPA_Eclipselink_OTM という名前のEclipse IDEでJPAプロジェクトを作成します。 このプロジェクトのすべてのモジュールは次のとおりです。

エンティティの作成

上記の図に従ってエンティティを作成します。 ‘src’ パッケージの下に ’com.tutorialspoin.eclipselink.entity’ という名前のパッケージを作成します。 指定されたパッケージの下に Department.java という名前のクラスを作成します。 クラスDepartmentエンティティは次のように表示されます。

package com.finddevguides.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;
   }
}

この関係の2番目のエンティティを作成します。 ‘com.finddevguides.eclipselink.entity’ パッケージの下に Employee.java という名前の従業員エンティティクラスがあります。 Employeeエンティティクラスは次のように表示されます。

package com.finddevguides.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

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.finddevguides.eclipselink.entity.Employee</class>
      <class>com.finddevguides.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>

サービスクラス

このモジュールには、属性の初期化を使用してリレーショナル部分を実装するサービスクラスが含まれています。 ‘com.finddevguides.eclipselink.service’ という名前の ‘src’ パッケージの下にパッケージを作成します。 OneToMany.java という名前のDAOクラスが、指定されたパッケージの下に作成されます。 DAOクラスは次のように表示されます。

package com.finddevguideseclipselink.service;

import java.util.List;
import java.util.ArrayList;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import com.finddevguides.eclipselink.entity.Department;
import com.finddevguides.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ワークベンチを次のように確認してください。 このプロジェクトでは、3つのテーブルが作成されます。

MySQLインターフェイスで次のクエリを渡すと、 department_employee テーブルの結果が表形式でクエリに次のように表示されます。

Select *from department_Id;

Department_Id   Employee_Eid
254         251
254         252
254         253

上記の表では、deparment_idおよびemployee_idフィールドは、部門および従業員のテーブルからの外部キー(参照フィールド)です。

MySQLインターフェイスで次のクエリを渡すと、クエリで表形式の部門テーブルの結果が次のように表示されます。

Select* from department;

Id  Name
254 Development

MySQLインターフェイスで次のクエリを渡すと、テーブル形式の従業員テーブルの結果がクエリで次のように表示されます。

Select *from employee;

Eid Deg                 Ename          Salary
251 Technical Writer    Satish         45000
252 Technical Writer    Krishna        45000
253 Technical Writer    Masthanvali    50000

@OneToOneリレーション

1対1の関係では、1つのアイテムは他の1つのアイテムにのみ属することができます。 これは、1つのエンティティの各行が別のエンティティの1つの行のみを参照することを意味します。

上記の例を考えてみましょう。* 従業員*と*部門*は逆方向の単方向で、リレーションは1対1リレーションです。 つまり、各従業員は1つの部門にのみ属します。 JPA_Eclipselink_OTO という名前のEclipse IDEでJPAプロジェクトを作成します。 このプロジェクトのすべてのモジュールは次のとおりです。

エンティティの作成

上記の図に従ってエンティティを作成します。 ‘src’ パッケージの下に ’com.tutorialspoin.eclipselink.entity’ という名前のパッケージを作成します。 指定されたパッケージの下に Department.java という名前のクラスを作成します。 クラスDepartmentエンティティは次のように表示されます。

package com.finddevguides.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;
   }
}

この関係の2番目のエンティティを作成します。 ‘com.finddevguides.eclipselink.entity’ パッケージの下に Employee.java という名前の従業員エンティティクラスがあります。 Employeeエンティティクラスは次のように表示されます。

package com.finddevguides.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

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.finddevguides.eclipselink.entity.Employee</class>
      <class>com.finddevguides.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>

サービスクラス

このモジュールには、属性の初期化を使用してリレーショナル部分を実装するサービスクラスが含まれています。 ‘com.finddevguides.eclipselink.service’ という名前の ‘src’ パッケージの下にパッケージを作成します。 OneToOne.java という名前のDAOクラスが、指定されたパッケージの下に作成されます。 DAOクラスは次のように表示されます。

package com.finddevguideseclipselink.service;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import com.finddevguides.eclipselink.entity.Department;
import com.finddevguides.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ワークベンチを確認してください。 上記の例では、2つのテーブルが作成されます。

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関係

多対多の関係では、1つのエンティティの1つ以上の行が他のエンティティの複数の行に関連付けられます。

ClassエンティティとTeacherエンティティ間の関係の例を考えてみましょう。 双方向の方法では、クラスと教師の両方が多対1の関係にあります。 つまり、クラスの各レコードは教師セット(教師ID)によって参照されます。教師セットは教師テーブルの主キーであり、Teacher_Classテーブルに格納されている必要があります。 ここでは、Teachers_Classテーブルに両方の外部キーフィールドが含まれています。* JPA_Eclipselink_MTM *という名前のEclipse IDEでJPAプロジェクトを作成します。 このプロジェクトのすべてのモジュールは次のとおりです。

@ManyToOne Relation

エンティティの作成

上記の図に従ってエンティティを作成します。 ‘src’ パッケージの下に ’com.tutorialspoin.eclipselink.entity’ という名前のパッケージを作成します。 指定されたパッケージの下に Clas.java という名前のクラスを作成します。 クラスDepartmentエンティティは次のように表示されます。

package com.finddevguides.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;
   }
}

この関係の2番目のエンティティを作成します- ‘com.finddevguides.eclipselink.entity’ パッケージの下に Teacher.java という名前の従業員エンティティクラス。 Employeeエンティティクラスは次のように表示されます。

package com.finddevguides.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

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.finddevguides.eclipselink.entity.Employee</class>
      <class>com.finddevguides.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>

サービスクラス

このモジュールには、属性の初期化を使用してリレーショナル部分を実装するサービスクラスが含まれています。 ‘com.finddevguides.eclipselink.service’ という名前の ‘src’ パッケージの下にパッケージを作成します。 ManyToMany.java という名前のDAOクラスが、指定されたパッケージの下に作成されます。 DAOクラスは次のように表示されます。

package com.finddevguides.eclipselink.service;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import com.finddevguides.eclipselink.entity.Clas;
import com.finddevguides.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ワークベンチを確認してください。 このサンプルプロジェクトでは、3つのテーブルが作成されます。

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は教師テーブルの外部キーであり、classet_cidはクラステーブルの外部キーです。 したがって、異なるクラスに異なる教師が割り当てられます。

MySQLインターフェイスで次のクエリを渡すと、テーブル形式の教師テーブルの結果がクエリで次のように表示されます。

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