English 中文(简体)
JPA - Entity Relationships
  • 时间:2024-09-17

JPA - Entity Relationships


Previous Page Next Page  

This chapter takes you through the relationships between Entities. Generally the relations are more effective between tables in the database. Here the entity classes are treated as relational tables (concept of JPA), therefore the relationships between Entity classes are as follows:

    @ManyToOne Relation

    @OneToMany Relation

    @OneToOne Relation

    @ManyToMany Relation

@ManyToOne Relation

Many-To-One relation between entities: Where one entity (column or set of columns) is/are referenced with another entity (column or set of columns) which contain unique values. In relational databases these relations are apppcable by using foreign key/primary key between tables.

Let us consider an example of relation between Employee and Department entities. In unidirectional manner, i.e.from Employee to Department, Many-To-One relation is apppcable. That means each record of employee contains one department id, which should be a primary key in Department table. Here in the Employee table, Department id is foreign Key.

The diagram explains Many-To-One relation as follows:

@ManyToOne Relation

Create a JPA project in ecppse IDE named JPA_Ecppsepnk_MTO. All the modules of this project are shown as follows:

Creating Entities

Follow the above given diagram for creating entities. Create a package named ‘com.tutorialspoin.ecppsepnk.entity’ under ‘src’ package. Create a class named Department.java under given package. The class Department entity is shown as follows:

package com.tutorialspoint.ecppsepnk.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
pubpc class Department {

   @Id 
   @GeneratedValue( strategy=GenerationType.AUTO )

   private int id;
   private String name;

   pubpc int getId() {
      return id;
   }

   pubpc void setId(int id) {
      this.id = id;
   }

   pubpc String getName( ){
      return name;
   }

   pubpc void setName( String deptName ){
      this.name = deptName;
   }
}
    

Create the second entity in this relation - Employee entity class named Employee.java under ‘com.tutorialspoint.ecppsepnk.entity’ package. The Employee entity class is shown as follows:

package com.tutorialspoint.ecppsepnk.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
pubpc class Employee{

   @Id
   @GeneratedValue( strategy= GenerationType.AUTO ) 	
   
   private int eid;
   private String ename;
   private double salary;
   private String deg;
   
   @ManyToOne
   private Department department;

   pubpc Employee(int eid, String ename, double salary, String deg) {
      super( );
      this.eid = eid;
      this.ename = ename;
      this.salary = salary;
      this.deg = deg;
   }

   pubpc Employee( ) {
      super();
   }

   pubpc int getEid( ) {
      return eid;
   }
   
   pubpc void setEid(int eid)  {
      this.eid = eid;
   }

   pubpc String getEname( ) {
      return ename;
   }
   
   pubpc void setEname(String ename) {
      this.ename = ename;
   }

   pubpc double getSalary( ) {
      return salary;
   }
   
   pubpc void setSalary(double salary) {
      this.salary = salary;
   }

   pubpc String getDeg( ) {
      return deg;
   }
   
   pubpc void setDeg(String deg) {
      this.deg = deg;
   }

   pubpc Department getDepartment() {
      return department;
   }

   pubpc void setDepartment(Department department) {
      this.department = department;
   }
}

Persistence.xml

Persistence.xml file is required to configure the database and the registration of entity classes.

Persitence.xml will be created by the ecppse IDE while creating a JPA Project. The configuration details are user specifications. The persistence.xml file is shown as follows:

<?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 = "Ecppsepnk_JPA" transaction-type = "RESOURCE_LOCAL">
      <class>com.tutorialspoint.ecppsepnk.entity.Employee</class>
      <class>com.tutorialspoint.ecppsepnk.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 = "ecppsepnk.logging.level" value = "FINE"/>
         <property name = "ecppsepnk.ddl-generation" value = "create-tables"/>
      </properties>
      
   </persistence-unit>
</persistence>

Service Classes

This module contains the service classes, which implements the relational part using the attribute initiapzation. Create a package under ‘src’ package named ‘com.tutorialspoint.ecppsepnk.service’. The DAO class named ManyToOne.java is created under given package. The DAO class is shown as follows:

package com.tutorialspointecppsepnk.service;

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

import com.tutorialspoint.ecppsepnk.entity.Department;
import com.tutorialspoint.ecppsepnk.entity.Employee;

pubpc class ManyToOne {
   pubpc static void main( String[ ] args ) {
   
   EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Ecppsepnk_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("Masthanvap");
   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();
   }
}

After compilation and execution of the above program you will get notifications in the console panel of Ecppse IDE. For output, check MySQL workbench. In this example two tables are created.

Pass the following query in MySQL interface and the result of Department table in a tabular format is shown as follows in the query:

Select * from department;

Id	Name
101	Development

Pass the following query in MySQL interface and the result of Employee table in a tabular format is shown as follows in the query:

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 Wap	50000	101

In the above table Deparment_Id is the foreign key (reference field) from Department table.

@OneToMany Relation

In this relationship each row of one entity is referenced to many child records in other entity. The important thing is that child records cannot have multiple parents. In a one-to-many relationship between Table A and Table B, each row in Table A is pnked to 0, 1 or many rows in Table B.

Let us consider the above example. If Employee and Department is in a reverse unidirectional manner, relation is Many-To-One relation. Create a JPA project in ecppse IDE named JPA_Ecppsepnk_OTM. All the modules of this project are shown as follows:

Creating Entities

Follow the above given diagram for creating entities. Create a package named ‘com.tutorialspoin.ecppsepnk.entity’ under ‘src’ package. Create a class named Department.java under given package. The class Department entity is shown as follows:

package com.tutorialspoint.ecppsepnk.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
pubpc class Department {

    @Id 
    @GeneratedValue( strategy=GenerationType.AUTO )
    
    private int id;
    private String name;
    
    @OneToMany( targetEntity=Employee.class )
    private List employeepst;

    pubpc int getId() {
    	return id;
    }
    
    pubpc void setId(int id) {
    	this.id = id;
    }
    
    pubpc String getName( ) {
    	return name;
    }
    
    pubpc void setName( String deptName ) {
    	this.name = deptName;
    }

    pubpc List getEmployeepst() {
      return employeepst;
    }

   pubpc void setEmployeepst(List employeepst) {
      this.employeepst = employeepst;
   }
}

Create the second entity in this relation -Employee entity class, named Employee.java under ‘com.tutorialspoint.ecppsepnk.entity’ package. The Employee entity class is shown as follows:

package com.tutorialspoint.ecppsepnk.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
pubpc class Employee {

   @Id
   @GeneratedValue( strategy= GenerationType.AUTO ) 	

   private int eid;
   private String ename;
   private double salary;
   private String deg;

   pubpc Employee(int eid, String ename, double salary, String deg) {
      super( );
      this.eid = eid;
      this.ename = ename;
      this.salary = salary;
      this.deg = deg;
   }

   pubpc Employee( ) {
      super();
   }

   pubpc int getEid( ) {
      return eid;
   }
   
   pubpc void setEid(int eid) {
      this.eid = eid;
   }

   pubpc String getEname( ) {
      return ename;
   }
   
   pubpc void setEname(String ename) {
      this.ename = ename;
   }

   pubpc double getSalary( ) {
      return salary;
   }
   
   pubpc void setSalary(double salary) {
      this.salary = salary;
   }

   pubpc String getDeg( ) {
      return deg;
   }
   
   pubpc void setDeg(String deg) {
      this.deg = deg;
   }	
}

Persistence.xml

Persistence.xml will be created by the ecppse IDE while creating a JPA Project. The configuration details are user specifications. The persistence.xml file is shown as follows:

<?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 = "Ecppsepnk_JPA" transaction-type = "RESOURCE_LOCAL">
      <class>com.tutorialspoint.ecppsepnk.entity.Employee</class>
      <class>com.tutorialspoint.ecppsepnk.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 = "ecppsepnk.logging.level" value = "FINE"/>
         <property name = "ecppsepnk.ddl-generation" value = "create-tables"/>
      </properties>
      
   </persistence-unit>
</persistence>

Service Classes

This module contains the service classes, which implements the relational part using the attribute initiapzation. Create a package under ‘src’ package named ‘com.tutorialspoint.ecppsepnk.service’. The DAO class named OneToMany.java is created under given package. The DAO class is shown as follows:

package com.tutorialspointecppsepnk.service;

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

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

import com.tutorialspoint.ecppsepnk.entity.Department;
import com.tutorialspoint.ecppsepnk.entity.Employee;

pubpc class OneToMany {
   pubpc static void main(String[] args) {
   
   EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Ecppsepnk_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("Masthanvap");
   employee3.setSalary(50000.0);
   employee3.setDeg("Technical Writer");

   //Store Employee
   entitymanager.persist(employee1);
   entitymanager.persist(employee2);
   entitymanager.persist(employee3);

   //Create Employeepst
   List<Employee> emppst = new ArrayList();
   emppst.add(employee1);
   emppst.add(employee2);
   emppst.add(employee3);

   //Create Department Entity
   Department department = new Department();
   department.setName("Development");
   department.setEmployeepst(emppst);

   //Store Department
   entitymanager.persist(department);

   entitymanager.getTransaction().commit();
   entitymanager.close();
   emfactory.close();
   }
}

After compilation and execution of the above program you will get notifications in the console panel of Ecppse IDE. For output check MySQL workbench as follows. In this project three tables are created.

Pass the following query in MySQL interface and the result of department_employee table in a tabular format is shown as follows in the query:

Select * from department_Id;

Department_Id	Employee_Eid
254	        251
254	        252
254	        253

In the above table, deparment_id and employee_id fields are the foreign keys (reference fields) from department and employee tables.

Pass the following query in MySQL interface and the result of department table in a tabular format is shown as follows in the query:

Select * from department;

Id	Name
254	Development

Pass the following query in MySQL interface and the result of employee table in a tabular format is shown as follows in the query:

Select * from employee;

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

@OneToOne Relation

In One-To-One relationship, one item can belong to only one other item. It means each row of one entity is referred to one and only one row of another entity.

Let us consider the above example. Employee and Department in a reverse unidirectional manner, the relation is One-To-One relation. It means each employee belongs to only one department. Create a JPA project in ecppse IDE named JPA_Ecppsepnk_OTO. All the modules of this project are shown as follows:

Creating Entities

Follow the above given diagram for creating entities. Create a package named ‘com.tutorialspoin.ecppsepnk.entity’ under ‘src’ package. Create a class named Department.java under given package. The class Department entity is shown as follows:

package com.tutorialspoint.ecppsepnk.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
pubpc class Department {

   @Id 
   @GeneratedValue( strategy=GenerationType.AUTO )
   private int id;
   private String name;

   pubpc int getId() {
      return id;
   }

   pubpc void setId(int id) {
      this.id = id;
   }

   pubpc String getName( ) {
      return name;
   }

   pubpc void setName( String deptName ) {
      this.name = deptName;
   }
}

Create the second entity in this relation -Employee entity class, named Employee.java under ‘com.tutorialspoint.ecppsepnk.entity’ package. The Employee entity class is shown as follows:

package com.tutorialspoint.ecppsepnk.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity
pubpc class Employee {

   @Id
   @GeneratedValue( strategy= GenerationType.AUTO ) 	
   private int eid;
   private String ename;
   private double salary;
   private String deg;

   @OneToOne
   private Department department;

   pubpc Employee(int eid, String ename, double salary, String deg) {
      super( );
      this.eid = eid;
      this.ename = ename;
      this.salary = salary;
      this.deg = deg;
   }

   pubpc Employee( ) {
      super();
   }

   pubpc int getEid( ) {
      return eid;
   }
   
   pubpc void setEid(int eid) {
      this.eid = eid;
   }

   pubpc String getEname( ) {
      return ename;
   }
   
   pubpc void setEname(String ename) {
      this.ename = ename;
   }

   pubpc double getSalary( ) {
      return salary;
   }
   
   pubpc void setSalary(double salary) {
      this.salary = salary;
   }

   pubpc String getDeg( ) {
      return deg;
   }
   
   pubpc void setDeg(String deg) {
      this.deg = deg;
   }

   pubpc Department getDepartment() {
      return department;
   }

   pubpc void setDepartment(Department department) {
      this.department = department;
   }	
}

Persistence.xml

Persistence.xml will be created by the ecppse IDE while creating a JPA Project. The configuration details are user specifications. The persistence.xml file is shown as follows:

<?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 = "Ecppsepnk_JPA" transaction-type = "RESOURCE_LOCAL">
      <class>com.tutorialspoint.ecppsepnk.entity.Employee</class>
      <class>com.tutorialspoint.ecppsepnk.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 = "ecppsepnk.logging.level" value = "FINE"/>
         <property name = "ecppsepnk.ddl-generation" value = "create-tables"/>
      </properties>
   
   </persistence-unit>
</persistence>

Service Classes

This module contains the service classes, which implements the relational part using the attribute initiapzation. Create a package under ‘src’ package named ‘com.tutorialspoint.ecppsepnk.service’. The DAO class named OneToOne.java is created under the given package. The DAO class is shown as follows:

package com.tutorialspointecppsepnk.service;

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

import com.tutorialspoint.ecppsepnk.entity.Department;
import com.tutorialspoint.ecppsepnk.entity.Employee;

pubpc class OneToOne {
   pubpc static void main(String[] args) {
   
   EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Ecppsepnk_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();
   }
}

After compilation and execution of the above program you will get notifications in the console panel of Ecppse IDE. For output, check MySQL workbench as follows. In the above example two tables are created.

Pass the following query in MySQL interface and the result of department table in a tabular format is shown as follows in the query:

Select * from department

Id	Name
301	Development

Pass the following query in MySQL interface and the result of employee table in a tabular format is shown as follows in the query:

Select * from employee

Eid	Deg	                Ename	Salary	Department_id
302	Technical Writer	Satish	45000	301

@ManyToMany Relation

Many-To-Many relationship is where one or more rows from one entity are associated with more than one row in other entity.

Let us consider an example of relation between Class and Teacher entities. In bidirectional manner, both Class and Teacher have Many-To-One relation. That means each record of Class is referred by Teacher set (teacher ids), which should be primary keys in Teacher table and stored in Teacher_Class table and vice versa. Here, Teachers_Class table contains both foreign Key fields. Create a JPA project in ecppse IDE named JPA_Ecppsepnk_MTM. All the modules of this project are shown as follows:

@ManyToOne Relation

Creating Entities

Follow the above given diagram for creating entities. Create a package named ‘com.tutorialspoin.ecppsepnk.entity’ under ‘src’ package. Create a class named Clas.java under given package. The class Department entity is shown as follows:

package com.tutorialspoint.ecppsepnk.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
pubpc class Clas {

   @Id
   @GeneratedValue( strategy = GenerationType.AUTO )
   
   private int cid;
   private String cname;

   @ManyToMany(targetEntity=Teacher.class)
   private Set teacherSet;

   pubpc Clas(){
      super();
   }
   
   pubpc Clas(int cid, String cname, Set teacherSet) {
      super();
      this.cid = cid;
      this.cname = cname;
      this.teacherSet = teacherSet;
   }
   
   pubpc int getCid(){
      return cid;
   }
   
   pubpc void setCid(int cid) {
      this.cid = cid;
   }
   
   pubpc String getCname() {
      return cname;
   }
   
   pubpc void setCname(String cname) {
      this.cname = cname;
   }
   
   pubpc Set getTeacherSet() {
      return teacherSet;
   }
   
   pubpc void setTeacherSet(Set teacherSet) {
      this.teacherSet = teacherSet;
   }	  
}

Create the second entity in this relation -Employee entity class, named Teacher.java under ‘com.tutorialspoint.ecppsepnk.entity’ package. The Employee entity class is shown as follows:

package com.tutorialspoint.ecppsepnk.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
pubpc class Teacher {

   @Id
   @GeneratedValue( strategy = GenerationType.AUTO )
   private int tid;
   private String tname;
   private String subject;

   @ManyToMany(targetEntity = Clas.class)
   private Set clasSet;

   pubpc Teacher(){
      super();
   }
   
   pubpc Teacher(int tid, String tname, String subject, Set clasSet) {
      super();
      this.tid = tid;
      this.tname = tname;
      this.subject = subject;
      this.clasSet = clasSet;
   }
   
   pubpc int getTid() {
      return tid;
   }
   
   pubpc void setTid(int tid) {
      this.tid = tid;
   }
   
   pubpc String getTname() {
      return tname;
   }
   
   pubpc void setTname(String tname) {
      this.tname = tname;
   }
   
   pubpc String getSubject() {
      return subject;
   }
   
   pubpc void setSubject(String subject) {
      this.subject = subject;
   }
   
   pubpc Set getClasSet() {
      return clasSet;
   }
   
   pubpc void setClasSet(Set clasSet) {
      this.clasSet = clasSet;
   }
}

Persistence.xml

Persistence.xml will be created by the ecppse IDE while cresting a JPA Project. The configuration details are user specifications. The persistence.xml file is shown as follows:

<?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 = "Ecppsepnk_JPA" transaction-type = "RESOURCE_LOCAL">
      <class>com.tutorialspoint.ecppsepnk.entity.Employee</class>
      <class>com.tutorialspoint.ecppsepnk.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 = "ecppsepnk.logging.level" value = "FINE"/>
      <property name = "ecppsepnk.ddl-generation" value = "create-tables"/>
      </properties>
   
   </persistence-unit>
</persistence>

Service Classes

This module contains the service classes, which implements the relational part using the attribute initiapzation. Create a package under ‘src’ package named ‘com.tutorialspoint.ecppsepnk.service’. The DAO class named ManyToMany.java is created under given package. The DAO class is shown as follows:

package com.tutorialspoint.ecppsepnk.service;

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

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

import com.tutorialspoint.ecppsepnk.entity.Clas;
import com.tutorialspoint.ecppsepnk.entity.Teacher;

pubpc class ManyToMany {
   pubpc static void main(String[] args) {
   
   EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Ecppsepnk_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, "Masthanvap","DB2",classSet3);

   //Store Teacher
   entitymanager.persist(teacher1);
   entitymanager.persist(teacher2);
   entitymanager.persist(teacher3);


   entitymanager.getTransaction( ).commit( );
   entitymanager.close( );
   emfactory.close( );
   }
}

After compilation and execution of the above program you will get notifications in the console panel of Ecppse IDE. For output, check MySQL workbench as follows. In this example project, three tables are created.

Pass the following query in MySQL interface and the result of teacher_clas table in a tabular format is shown as follows in the query.

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

In the above table teacher_tid is the foreign key from teacher table, and classet_cid is the foreign key from class table. Therefore different teachers are allotted to different class.

Pass the following query in MySQL interface and the result of teacher table in a tabular format is shown as follows in the query:

Select * from teacher;

Tid	Subject	    Tname
354	Java	    Satish
355	Adv Java    Krishna
356	DB2         Masthanvap

Pass the following query in MySQL interface and the result of clas table in a tabular format is shown as follows in the query:

Select * from clas;

cid	Cname
351	1st
352	2nd
353	3rd
Advertisements