JPA - Quick Guide



JPA - Introduction

Any enterprise application performs database operations by storing and retrieving vast amounts of data. Despite all the available technologies for storage management, application developers normally struggle to perform database operations efficiently.

Generally, Java developers use lots of code, or use the proprietary framework to interact with the database, whereas using JPA, the burden of interacting with the database reduces significantly. It forms a bridge between object models (Java program) and relational models (database program).

Mismatches between relational and object models

Relational objects are represented in a tabular format, while object models are represented in an interconnected graph of object format. While storing and retrieving an object model from a relational database, some mismatch occurs due to the following reasons:

  • Granularity : Object model has more granularity than relational model.

  • Subtypes : Subtypes (means inheritance) are not supported by all types of relational databases.

  • Identity : Like object model, relational model does not expose identity while writing equality.

  • Associations : Relational models cannot determine multiple relationships while looking into an object domain model.

  • Data navigation : Data navigation between objects in an object network is different in both models.

What is JPA?

Java Persistence API is a collection of classes and methods to persistently store the vast amounts of data into a database which is provided by the Oracle Corporation.

Where to use JPA?

To reduce the burden of writing codes for relational object management, a programmer follows the JPA Provider framework, which allows easy interaction with database instance. Here the required framework is taken over by JPA.

JPA

JPA History

Earlier versions of EJB, defined persistence layer combined with business logic layer using javax.ejb.EntityBean Interface.

  • While introducing EJB 3.0, the persistence layer was separated and specified as JPA 1.0 (Java Persistence API). The specifications of this API were released along with the specifications of JAVA EE5 on May 11, 2006 using JSR 220.

  • JPA 2.0 was released with the specifications of JAVA EE6 on December 10, 2009 as a part of Java Community Process JSR 317.

  • JPA 2.1 was released with the specification of JAVA EE7 on April 22, 2013 using JSR 338.

  • JPA 2.2 was released as a maintenance release in summer of 2017.

  • JPA 3.0 as part of Java EE project was transferred from Oracle to Eclipse Foundation and renamed as Jakarta EE. Packages were renamed from javax.persistence to jakarta.persistence.

  • Jakarta Persistance 3.1 was released in Sep'2022 as part of Jakarta EE 10

  • Jakarta Persistance 3.2 was released in Spring of 2024 as part of Jakarta EE 11

JPA Providers

JPA is an open source API, therefore various enterprise vendors such as Oracle, Redhat, Eclipse, etc. provide new products by adding the JPA persistence flavor in them. Some of these products include:

Hibernate, Eclipselink, Toplink, Spring Data JPA, etc.

JPA - Architecture

Java Persistence API is a source to store business entities as relational entities. It shows how to define a PLAIN OLD JAVA OBJECT (POJO) as an entity and how to manage entities with relations.

Class Level Architecture

The following image shows the class level architecture of JPA. It shows the core classes and interfaces of JPA.

JPA Class Level Architecture

The following table describes each of the units shown in the above architecture.

Units Description
EntityManagerFactory This is a factory class of EntityManager. It creates and manages multiple EntityManager instances.
EntityManager It is an Interface, it manages the persistence operations on objects. It works like factory for Query instance.
Entity Entities are the persistence objects, stores as records in the database.
EntityTransaction It has one-to-one relationship with EntityManager. For each EntityManager, operations are maintained by EntityTransaction class.
Persistence This class contain static methods to obtain EntityManagerFactory instance.
Query This interface is implemented by each JPA vendor to obtain relational objects that meet the criteria.

The above classes and interfaces are used for storing entities into a database as a record. They help programmers by reducing their efforts to write codes for storing data into a database so that they can concentrate on more important activities such as writing codes for mapping the classes with database tables.

JPA Class Relationships

In the above architecture, the relations between the classes and interfaces belong to the javax.persistence package. The following diagram shows the relationship between them.

JPA Class Relationships
  • The relationship between EntityManagerFactory and EntityManager is one-to-many. It is a factory class to EntityManager instances.

  • The relationship between EntityManager and EntityTransaction is one-to-one. For each EntityManager operation, there is an EntityTransaction instance.

  • The relationship between EntityManager and Query is one-to-many. Many number of queries can execute using one EntityManager instance.

  • The relationship between EntityManager and Entity is one-to-many. One EntityManager instance can manage multiple Entities.

JPA - ORM Components

Most contemporary applications use relational database to store data. Recently, many vendors switched to object database to reduce their burden on data maintenance. It means object database or object relational technologies are taking care of storing, retrieving, updating, and maintenance. The core part of this object relational technologies are mapping orm.xml file. As xml does not require compilation, we can easily make changes to multiple data sources with less administration.

Object Relational Mapping

Object Relational Mapping (ORM) briefly tells you about what is ORM and how it works. ORM is a programming ability to covert data from object type to relational type and vice versa.

The main feature of ORM is mapping or binding an object to its data in the database. While mapping we have to consider the data, type of data and its relations with its self-entity or entity in any other table.

Advanced Features

  • Idiomatic persistence : It enables you to write the persistence classes using object oriented classes.

  • High Performance : It has many fetching techniques and hopeful locking techniques.

  • Reliable : It is highly stable and eminent. Used by many industrial programmers.

ORM Architecture

Here follow the ORM architecture.

Object Relational Mapping

The above architecture explains how object data is stored into relational database in three phases.

Phase1

The first phase, named as the Object data phase contains POJO classes, service interfaces and classes. It is the main business component layer, which has business logic operations and attributes.

For example let us take an employee database as schema −

  • Employee POJO class contain attributes such as ID, name, salary, and designation. And methods like setter and getter methods of those attributes.

  • Employee DAO/Service classes contains service methods such as create employee, find employee, and delete employee.

Phase 2

The second phase named as mapping or persistence phase which contains JPA provider, mapping file (ORM.xml), JPA Loader, and Object Grid.

  • JPA Provider : The vendor product which contains JPA flavor (javax.persistence). For example Eclipselink, Toplink, Hibernate, etc.

  • Mapping file : The mapping file (ORM.xml) contains mapping configuration between the data in a POJO class and data in a relational database.

  • JPA Loader : The JPA loader works like cache memory, which can load the relational grid data. It works like a copy of database to interact with service classes for POJO data (Attributes of POJO class).

  • Object Grid : The Object grid is a temporary location which can store the copy of relational data, i.e. like a cache memory. All queries against the database is first effected on the data in the object grid. Only after it is committed, it effects the main database.

Phase 3

The third phase is the Relational data phase. It contains the relational data which is logically connected to the business component. As discussed above, only when the business component commit the data, it is stored into the database physically. Until then the modified data is stored in a cache memory as a grid format. Same is the process for obtaining data.

The mechanism of the programmatic interaction of above three phases is called as object relational mapping.

Mapping.xml

The mapping.xml file is to instruct the JPA vendor for mapping the Entity classes with database tables.

Let us take an example of Employee entity which contains four attributes. The POJO class of Employee entity named Employee.java is as follows:

Employee.java

public class Employee {

   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;
   }
}

The above code is the Employee entity POJO class. It contain four attributes eid, ename, salary, and deg. Consider these attributes are the table fields in the database and eid is the primary key of this table. Now we have to design hibernate mapping file for it. The mapping file named mapping.xml is as follows:

mapping.xml

<? xml version="1.0" encoding="UTF-8" ?>

<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm    
   http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"
   version="1.0">
      
   <description> XML Mapping file</description>
      
   <entity class="Employee">        
      <table name="EMPLOYEETABLE"/>
      <attributes>
      
         <id name="eid">
            <generated-value strategy="TABLE"/>
         </id>

         <basic name="ename">
            <column name="EMP_NAME" length="100"/>
         </basic>
         
         <basic name="salary">
         </basic>
         
         <basic name="deg">
         </basic>
         
      </attributes>
   </entity>
   
</entity-mappings>

The above script for mapping the entity class with database table. In this file

  • <entity-mappings> : tag defines the schema definition to allow entity tags into xml file.

  • <description> : tag defines description about application.

  • <entity> : tag defines the entity class which you want to convert into table in a database. Attribute class defines the POJO entity class name.

  • <table> : tag defines the table name. If you want to keep class name as table name then this tag is not necessary.

  • <attributes> : tag defines the attributes (fields in a table).

  • <id> : tag defines the primary key of the table. The <generated-value> tag defines how to assign the primary key value such as Automatic, Manual, or taken from Sequence.

  • <basic> : tag is used for defining remaining attributes for table.

  • <column-name> : tag is used to define user defined table field name.

Annotations

Generally Xml files are used to configure specific component, or mapping two different specifications of components. In our case, we have to maintain xml separately in a framework. That means while writing a mapping xml file we need to compare the POJO class attributes with entity tags in mapping.xml file.

Here is the solution: In the class definition, we can write the configuration part using annotations. The annotations are used for classes, properties, and methods. Annotations starts with @ symbol. Annotations are declared before the class, property or method is declared. All annotations of JPA are defined in javax.persistence package.

Here follows the list of annotations used in our examples

Annotation Description
@Entity This annotation specifies to declare the class as entity or a table.
@Table This annotation specifies to declare table name.
@Basic This annotation specifies non constraint fields explicitly.
@Embedded This annotation specifies the properties of class or an entity whose value instance of an embeddable class.
@Id This annotation specifies the property, use for identity (primary key of a table) of the class.
@GeneratedValue This annotation specifies, how the identity attribute can be initialized such as Automatic, manual, or value taken from sequence table.
@Transient This annotation specifies the property which in not persistent i.e. the value is never stored into database.
@Column This annotation is used to specify column or attribute for persistence property.
@SequenceGenerator This annotation is used to define the value for the property which is specified in @GeneratedValue annotation. It creates a sequence.
@TableGenerator This annotation is used to specify the value generator for property specified in @GeneratedValue annotation. It creates a table for value generation.
@AccessType This type of annotation is used to set the access type. If you set @AccessType(FIELD) then Field wise access will occur. If you set @AccessType(PROPERTY) then Property wise assess will occur.
@JoinColumn This annotation is used to specify an entity association or entity collection. This is used in many- to-one and one-to-many associations.
@UniqueConstraint This annotation is used to specify the field, unique constraint for primary or secondary table.
@ColumnResult This annotation references the name of a column in the SQL query using select clause.
@ManyToMany This annotation is used to define a many-to-many relationship between the join Tables.
@ManyToOne This annotation is used to define a many-to-one relationship between the join Tables.
@OneToMany This annotation is used to define a one-to-many relationship between the join Tables.
@OneToOne This annotation is used to define a one-to-one relationship between the join Tables.
@NamedQueries This annotation is used for specifying list of named queries.
@NamedQuery This annotation is used for specifying a Query using static name.

Java Bean Standard

Java class, encapsulates the instance values and behaviors into a single unit callled object. Java Bean is a temporary storage and reusable component or an object. It is a serializable class which has default constructor and getter & setter methods to initialize the instance attributes individually.

Bean Conventions

  • Bean contains the default constructor or a file that contains serialized instance. Therefore, a bean can instantiate the bean.

  • The properties of a bean can be segregated into Boolean properties and non-Boolean properties.

  • Non-Boolean property contains getter and setter methods.

  • Boolean property contain setter and is method.

  • Getter method of any property should start with small lettered get (java method convention) and continued with a field name that starts with capital letter. E.g. the field name is salary therefore the getter method of this field is getSalary ().

  • Setter method of any property should start with small lettered set (java method convention), continued with a field name that starts with capital letter and the argument value to set to field. E.g. the field name is salary therefore the setter method of this field is setSalary (double sal).

  • For Boolean property, is method to check if it is true or false. E.g. the Boolean property empty, the is method of this field is isEmpty ().

JPA - Installation

This chapter will guide you on how to prepare a development environment to start your work with JPA. It will also teach you how to set up JDK on your machine before you set up JPA −

Setup Java Development Kit (JDK)

You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.

If you are running Windows and have installed the JDK in C:\jdk-24, you would have to put the following line in your C:\autoexec.bat file.

set PATH=C:\jdk-24;%PATH% 
set JAVA_HOME=C:\jdk-24

Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button.

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-24 and you use the C shell, you will have to put the following into your .cshrc file.

setenv PATH /usr/local/jdk-24/bin:$PATH 
setenv JAVA_HOME /usr/local/jdk-24

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.

Popular Java Editors

To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −

  • Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.

  • Netbeans − It is a Java IDE that is open-source and free, which can be downloaded from www.netbeans.org/index.html.

  • Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.

Installing JPA

You can go through the JPA installation by using any of the JPA Provider from this tutorial, E.g. Eclipselink, Hibernate. Let us follow the JPA installation using Eclipselink. For JPA programming we require to follow the specific folder framework therefore it is better to use IDE.

Download Eclipse IDE form following link https://www.eclipse.org/downloads/ Choose the EclipseIDE for JavaEE developer that is Eclipse indigo.

Unzip the Eclipse zip file in C drive. Open Eclipse IDE.

Installing JPA

Installing JPA using Eclipselink

Eclipselink is a library therefore we cannot add it directly to Eclipse IDE. For installing JPA using Eclipselink you need to follow the following steps.

  • Create a new JPA project by selecting File->New->JPA Project in the Eclipse IDE as follows:

    New JPA
  • You will get a dialog box named New JPA Project. Enter project name tutorialspoint_JPA_Eclipselink, check the jre version and click next:

    Dialog Box
  • Click on download library (if you do not have the library) in the user library section:

    Download Library
  • Select the latest version of Eclipselink library in the Download library dialog box and click next as follows:

    Download Library Dialog Box
  • Accept the terms of license and click finish for download library as follows:

    License
  • You will find the process of downloading a file as follows:

    Process
  • After downloading, select the downloaded library in the user library section and click finish as follows:

    Library Section
  • Finally you get the project file in the Package Explorer in Eclipse IDE. Extract all files, you will get the folder and file hierarchy as follows:

    Package Explorer

Adding MySQL connector to Project

Any example that we discuss here are mandatory to mingle with database. Let us consider MySQL database for database operations. It requires mysql-connector jar to interact with java program.

Follow the steps to configure database jar to your project.

  • Go to Project properties -> Java Build Path by right click on it. You will get a dialog box as follows: Click on Add External Jars.

    External Jars
  • Go to the jar location in your system memory, select and click on open as follows:

    Jar Location
  • Click ok on properties dialog. You will get the MySQL-connector Jar into your project. Now you are able to do database operations using MySQL.

JPA - Entity Managers

This chapter takes you through simple example with JPA. Let us consider employee management as example. It means the employee management is creating, updating, finding, and deleting an employee. As mentioned above we are using MySQL database for database operations.

The main modules for this example are as follows:

  • Model or POJO

    Employee.java

  • Persistence

    Persistence.xml

  • Service

    CreatingEmployee.java

    UpdatingEmployee.java

    FindingEmployee.java

    DeletingEmployee.java

Let us take the package hierarchy which we have used in the JPA installation with Eclipselink. Follow the hierarchy for this example as below:

Package Hierarchy

Creating Entities

Entities are nothing but beans or Models, in this example we will use Employee as entity. eid, ename, salary, and deg are the attributes of this entity. It contains default constructor, setter and getter methods of those attributes.

In the above shown hierarchy, create a package named com.tutorialspoint.eclipselink.entity, under src (Source) package. Create a class named Employee.java under given package as follows:

Employee.java

package com.tutorialspoint.eclipselink.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table
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;
   }
   
   @Override
   public String toString() {
      return "Employee [eid=" + eid + ", ename=" + ename + ", salary=" + salary + ", deg=" + deg + "]";
   }
}

In the above code, we have used @Entity annotation to make this POJO class as entity.

Before going to next module we need to create database for relational entity, which will register the database in persistence.xml file. Open MySQL workbench and type query as follows:

create database jpadb
use jpadb

Persistence.xml

This module plays a crucial role in the concept of JPA. In this xml file we will register the database and specify the entity class.

In the above shown package hierarchy, persistence.xml under JPA Content package is as follows:

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="3.0" xmlns="https://jakarta.ee/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd">
	<persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
	<class>com.tutorialspoint.eclipselink.entity.Employee</class>

      <properties>
         <property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/>
         <property name="jakarta.persistence.jdbc.user" value="guest"/>
         <property name="jakarta.persistence.jdbc.password" value="guest123"/>
         <property name="jakarta.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>

In the above xml, <persistence-unit> tag is defined with specific name for JPA persistence. The <class> tag defines entity class with package name. The <properties> tag defines all the properties, and <property> tag defines each property such as database registration, URL specification, username, and password. These are the Eclipselink properties. This file will configure the database.

Persistence Operations

Persistence operations are used against database and they are load and store operations. In a business component all the persistence operations fall under service classes.

In the above shown package hierarchy, create a package named com.tutorialspoint.eclipselink.service, under src (source) package. All the service classes named as CreateEmloyee.java, UpdateEmployee.java, FindEmployee.java, and DeleteEmployee.java. comes under the given package.

After completion of all the modules in this example, the package and file hierarchy is shown as follows:

Modules

JPA - Create Employee Example

This chapter takes you through simple example with JPA to create an Employee record in the MySQL database. We've created Employee.java as entity and persistence.xml in Entity Managers chapter.

Now let's create a service to create an employee in the database.

Example - Create Employee

CreateEmployee.java

package com.tutorialspoint.eclipselink.service;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.Employee;

public class CreateEmployee {

   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      
      EntityManager entitymanager = emfactory.createEntityManager( );
      entitymanager.getTransaction( ).begin( );

      Employee employee = new Employee( ); 
      employee.setEid( 1201 );
      employee.setEname( "Gopal" );
      employee.setSalary( 40000 );
      employee.setDeg( "Technical Manager" );
      
      entitymanager.persist( employee );
      entitymanager.getTransaction( ).commit( );

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

In the above code the createEntityManagerFactory () creates a persistence unit by providing the same unique name which we provide for persistence-unit in persistent.xml file. The entitymanagerfactory object will create the entitymanger instance by using createEntityManager () method. The entitymanager object creates entitytransaction instance for transaction management. By using entitymanager object, we can persist entities into database.

Output

Run the code as Java Application in Eclipse IDE.

After compilation and execution of the above program you will get notifications from eclipselink library on the console panel of eclipse IDE.

For result, open the MySQL workbench and type the following queries.

use jpadb
select * from employee

The effected database table named employee will be shown in a tabular format as follows:

Eid Ename Salary Deg
1201 Gopal 40000 Technical Manager

JPA - Update Employee Example

This chapter takes you through simple example with JPA to update an Employee record in the MySQL database. We've created Employee.java as entity and persistence.xml in Entity Managers chapter.

Now let's create a service to update an employee in the database.

Update Employee

To Update an employee, we need to get record form database, make changes, and finally commit it. The class named UpdateEmployee.java is shown as follows:

UpdateEmployee.java

package com.tutorialspoint.eclipselink.service;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.Employee;

public class UpdateEmployee {
   public static void main( String[ ] args ) {
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      
      EntityManager entitymanager = emfactory.createEntityManager( );
      entitymanager.getTransaction( ).begin( );
      Employee employee = entitymanager.find( Employee.class, 1201 );
      
      //before update
      System.out.println( employee );
      employee.setSalary( 46000 );
      entitymanager.getTransaction( ).commit( );
      
      //after update
      System.out.println( employee );
      entitymanager.close();
      emfactory.close();
   }
}

Output

After compilation and execution of the above program you will get notifications from Eclipselink library on the console panel of eclipse IDE.

For result, open the MySQL workbench and type the following queries.

use jpadb
select * from employee

The effected database table named employee will be shown in a tabular format as follows:

Eid Ename Salary Deg
1201 Gopal 46000 Technical Manager

The salary of employee, 1201 is updated to 46000.

JPA - Find Employee Example

This chapter takes you through simple example with JPA to search an Employee record in the MySQL database. We've created Employee.java as entity and persistence.xml in Entity Managers chapter.

Now let's create a service to find an employee in the database.

Example - Find Employee

To Find an employee we will get record from database and display it. In this operation, EntityTransaction is not involved any transaction is not applied while retrieving a record.

The class named FindEmployee.java as follows.

FindEmployee.java

package com.tutorialspoint.eclipselink.service;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.Employee;

public class FindEmployee {
   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager();
      Employee employee = entitymanager.find( Employee.class, 1201 );

      System.out.println("employee ID = " + employee.getEid( ));
      System.out.println("employee NAME = " + employee.getEname( ));
      System.out.println("employee SALARY = " + employee.getSalary( ));
      System.out.println("employee DESIGNATION = " + employee.getDeg( ));
   }
}

Output

After compilation and execution of the above program you will get output from Eclipselink library on the console panel of eclipse IDE as follows:

employee ID = 1201
employee NAME = Gopal
employee SALARY = 46000.0
employee DESIGNATION = Technical Manager

JPA - Delete Employee Example

This chapter takes you through simple example with JPA to delete an Employee record in the MySQL database. We've created Employee.java as entity and persistence.xml in Entity Managers chapter.

Now let's create a service to delete an employee in the database.

Example - Deleting Employee

To Delete an Employee, first we will find the record and then delete it. Here EntityTransaction plays an important role.

The class named DeleteEmployee.java as follows:

DeleteEmployee.java

package com.tutorialspoint.eclipselink.service;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.Employee;

public class DeleteEmployee {
   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager( );
      entitymanager.getTransaction( ).begin( );
      
      Employee employee = entitymanager.find( Employee.class, 1201 );
      entitymanager.remove( employee );
      entitymanager.getTransaction( ).commit( );
      entitymanager.close( );
      emfactory.close( );
   }
}

Output

After compilation and execution of the above program you will get notifications from Eclipselink library on the console panel of eclipse IDE.

For result, open the MySQL workbench and type the following queries.

use jpadb
select * from employee

The effected database table named employee will have null records.

JPA - Criteria API

Overview

The Criteria API is a predefined API used to define queries for entities. It is the alternative way of defining a JPQL query. These queries are type-safe, and portable and easy to modify by changing the syntax. Similar to JPQL it follows abstract schema (easy to edit schema) and embedded objects. The metadata API is mingled with criteria API to model persistent entity for criteria queries.

The major advantage of the criteria API is that errors can be detected earlier during compile time. String based JPQL queries and JPA criteria based queries are same in performance and efficiency.

History of criteria API

The criteria API is included into all versions of JPA therefore each step of criteria API is notified in the specifications of JPA.

  • In JPA 2.0, the criteria query API, standardization of queries are developed.

  • In JPA 2.1, Criteria update and delete (bulk update and delete) are included.

Criteria Query Structure

The Criteria API and the JPQL are closely related and are allowed to design using similar operators in their queries. It follows jakarta.persistence.criteria package to design a query. The query structure means the syntax criteria query.

The following simple criteria query returns all instances of the entity class in the data source.

EntityManager em = ...;
CriteriaBuilder cb = em.getCriteriaBuilder();

CriteriaQuery<Entity class> cq = cb.createQuery(Entity.class);
Root<Entity> from = cq.from(Entity.class);

cq.select(Entity);
TypedQuery<Entity> q = em.createQuery(cq);
List<Entity> allitems = q.getResultList();

The query demonstrates the basic steps to create a criteria.

  • EntityManager instance is used to create a CriteriaBuilder object.

  • CriteriaQuery instance is used to create a query object. This query objects attributes will be modified with the details of the query.

  • CriteriaQuery.from method is called to set the query root.

  • CriteriaQuery.select is called to set the result list type.

  • TypedQuery<T> instance is used to prepare a query for execution and specifying the type of the query result.

  • getResultList method on the TypedQuery<T> object to execute a query. This query returns a collection of entities, the result is stored in a List.

Example of criteria API

Let us consider the example of employee database. Let us assume the jpadb.employee table contains following records:

Eid	Ename           Salary	Deg
401	Gopal	        40000	Technical Manager
402	Manisha	        40000	Proof reader
403	Masthanvali     35000	Technical Writer
404 Satish	        30000	Technical writer
405	Krishna	        30000	Technical Writer
406	Kiran	        35000	Proof reader

Creating Entities

Follow the above given diagram for creating entities. Create a package named com.tutorialspoin.eclipselink.entity under src package if not present. Create a class named Employee.java under given package. The class Employee entity is shown as follows:

Employee.java

package com.tutorialspoint.eclipselink.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.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;
   }
   
   @Override
   public String toString() {
   return "Employee [eid = " + eid + ", ename = " + ename + ", salary = " + salary + ", deg = " + deg + "]";
   }
}

Persistence.xml

Persistence.xml will be created by the eclipse 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="3.0" xmlns="https://jakarta.ee/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd">
	<persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
	<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
	<class>com.tutorialspoint.eclipselink.entity.Employee</class>
      <properties>
         <property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/>
         <property name="jakarta.persistence.jdbc.user" value="guest"/>
         <property name="jakarta.persistence.jdbc.password" value="guest123"/>
         <property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
         <property name="eclipselink.logging.level" value="FINE"/>
         <property name="eclipselink.ddl-generation" value="create-tables"/>
      </properties>
	</persistence-unit>
</persistence>

Service Classes

This module contains the service classes, which implements the Criteria query part using the MetaData API initialization. Create a package named com.tutorialspoint.eclipselink.service. The class named CriteriaAPI.java is created under given package. The DAO class is shown as follows:

CriteriaApi.java

package com.tutorialspoint.eclipselink.service;

import java.util.List;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;

import com.tutorialspoint.eclipselink.entity.Employee;

public class CriteriaApi {
   public static void main(String[] args) {
   
   EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
   EntityManager entitymanager = emfactory.createEntityManager( );
   CriteriaBuilder criteriaBuilder = entitymanager.getCriteriaBuilder();
   CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
   Root<Employee> from = criteriaQuery.from(Employee.class);

   //select all records
   System.out.println("Select all records");
   CriteriaQuery<Object> select = criteriaQuery.select(from);
   TypedQuery<Object> typedQuery = entitymanager.createQuery(select);
   List<Object> resultlist = typedQuery.getResultList();

   for(Object o:resultlist) {
      Employee e = (Employee)o;
      System.out.println("EID : " + e.getEid() + " Ename : " + e.getEname());
   }

   //Ordering the records 
   System.out.println("Select all records by follow ordering");
   CriteriaQuery<Object> select1 = criteriaQuery.select(from);
   select1.orderBy(criteriaBuilder.asc(from.get("ename")));
   TypedQuery<Object> typedQuery1 = entitymanager.createQuery(select);
   List<Object> resultlist1 = typedQuery1.getResultList();

   for(Object o:resultlist1){
      Employee e=(Employee)o;
      System.out.println("EID : " + e.getEid() + " Ename : " + e.getEname());
   }

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

Output

After compilation and execution of the above program you will get output in the console panel of Eclipse IDE as follows:

Select All records
EID : 401 Ename : Gopal
EID : 402 Ename : Manisha
EID : 403 Ename : Masthanvali
EID : 404 Ename : Satish
EID : 405 Ename : Krishna
EID : 406 Ename : Kiran
Select All records by follow Ordering
EID : 401 Ename : Gopal
EID : 406 Ename : Kiran
EID : 405 Ename : Krishna
EID : 402 Ename : Manisha
EID : 403 Ename : Masthanvali
EID : 404 Ename : Satish

JPA - JPQL

This chapter tells you about JPQL and how it works with persistence units. In this chapter, examples follow the same package hierarchy, which we used in the previous chapter as follows:

JPA JPQL

Java Persistence Query language

JPQL is Java Persistence Query Language defined in JPA specification. It is used to create queries against entities to store in a relational database. JPQL is developed based on SQL syntax. But it wont affect the database directly.

JPQL can retrieve information or data using SELECT clause, can do bulk updates using UPDATE clause and DELETE clause. EntityManager.createQuery() API will support for querying language.

Query Structure

JPQL syntax is very similar to the syntax of SQL. Having SQL like syntax is an advantage because SQL is a simple structured query language and many developers are using it in applications. SQL works directly against relational database tables, records and fields, whereas JPQL works with Java classes and instances.

For example, a JPQL query can retrieve an entity object rather than field result set from database, as with SQL. The JPQL query structure as follows.

SELECT ... FROM ...
[WHERE ...]
[GROUP BY ... [HAVING ...]]
[ORDER BY ...]

The structure of JPQL DELETE and UPDATE queries is simpler as follows.

DELETE FROM ... [WHERE ...]
 
UPDATE ... SET ... [WHERE ...]

Scalar and Aggregate Functions

Scalar functions returns resultant values based on input values. Aggregate functions returns the resultant values by calculating the input values.

Follow the same example employee management used in previous chapters. Here we will go through the service classes using scalar and aggregate functions of JPQL.

Let us assume the jpadb.employee table contains following records.

Eid Ename Salary Deg
1201 Gopal 40000 Technical Manager
1202 Manisha 40000 Proof Reader
1203 Masthanvali 40000 Technical Writer
1204 Satish 30000 Technical Writer
1205 Krishna 30000 Technical Writer
1206 Kiran 35000 Proof Reader

Eager and Lazy Loading

The main concept of JPA is to make a duplicate copy of the database in cache memory. While transacting with the database, first it will effect on duplicate data and only when it is committed using entity manager, the changes are effected into the database.

There are two ways of fetching records from the database - eager fetch and lazy fetch.

Eager fetch

Fetching the whole record while finding the record using Primary Key.

Lazy fetch

It checks for the availability of notifies it with primary key if it exists. Then later if you call any of the getter method of that entity then it fetches the whole.

But lazy fetch is possible when you try to fetch the record for the first time. That way, a copy of the whole record is already stored in cache memory. Performance wise, lazy fetch is preferable.

Prepare Data

Let us assume the jpadb.employee table contains following records. We're going to use this table in coming chapters' examples.

Eid Ename Salary Deg
1201 Gopal 40000 Technical Manager
1202 Manisha 40000 Proof Reader
1203 Masthanvali 40000 Technical Writer
1204 Satish 30000 Technical Writer
1205 Krishna 30000 Technical Writer
1206 Kiran 35000 Proof Reader

JPA - Scalar Function

Scalar functions return resultant values based on input values. For example, Upper() function returns the passed column value in upper case.

Following the same example employee management used in previous chapters, we will go through the service classes using scalar functions of JPQL.

Example - Usage of Upper() Scalar Function using JPA

Create a class named ScalarFunction.java under com.tutorialspoint.eclipselink.service package as follows−

ScalarFunction.java

package com.tutorialspoint.eclipselink.service;

import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;

public class ScalarFunction {
   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager();

      //Scalar function
      Query query = entitymanager.createQuery("Select UPPER(e.ename) from Employee e");
      List<String> list = query.getResultList();

      for(String e:list) {
         System.out.println("Employee NAME :"+e);
      }
   }
}

Output

Run the code as Java Application in Eclipse IDE.

After compilation and execution of the above program you will get following result on the console panel of eclipse IDE.

Employee NAME :GOPAL
Employee NAME :MANISHA
Employee NAME :MASTHANVALI
Employee NAME :SATISH
Employee NAME :KRISHNA
Employee NAME :KIRAN

JPA - Aggregate Function

Aggregate functions return resultant values by calculating result based on input values. For example, Max() function returns the maximum of passed column value.

Following the same example employee management used in previous chapters, we will go through the service classes using aggregate functions of JPQL.

Example - Usage of Max() Aggregate Function using JPA

Create a class named AggregateFunction.java under com.tutorialspoint.eclipselink.service package as follows−

Aggregate.java

package com.tutorialspoint.eclipselink.service;

import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;

public class AggregateFunction {
   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager();

      //Aggregate function
      Query query1 = entitymanager.createQuery("Select MAX(e.salary) from Employee e");
      Double result = (Double) query1.getSingleResult();
      System.out.println("Max Employee Salary: " + result);
   }
}

Output

Run the code as Java Application in Eclipse IDE.

After compilation and execution of the above program you will get following result on the console panel of eclipse IDE.

Max Employee Salary: 40000.0

JPA - Between Keyword

Between keyword is used with Where clause in a query to filter out records lying between certain range of values.

Following the same example employee management used in previous chapters, we will go through the service classes using between keyword of JPQL.

Example - Usage of Between keyword using JPA

Create a class named BetweenDemo.java under com.tutorialspoint.eclipselink.service package as follows−

BetweenDemo.java

package com.tutorialspoint.eclipselink.service;

import java.util.List;

import com.tutorialspoint.eclipselink.entity.Employee;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;

public class BetweenDemo {
   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager();

      //Between
      Query query = entitymanager.createQuery( "Select e " + "from Employee e " + "where e.salary " + "Between 30000 and 40000" );
      
      List<Employee> list=(List<Employee>)query.getResultList( );

      for( Employee e:list ){
         System.out.print("Employee ID :" + e.getEid( ));
         System.out.println("\t Employee salary :" + e.getSalary( ));
      }
   }
}

Output

Run the code as Java Application in Eclipse IDE.

After compilation and execution of the above program you will get following result on the console panel of eclipse IDE.

Employee ID :1201	 Employee salary :40000.0
Employee ID :1202	 Employee salary :40000.0
Employee ID :1203	 Employee salary :40000.0
Employee ID :1204	 Employee salary :30000.0
Employee ID :1205	 Employee salary :30000.0
Employee ID :1206	 Employee salary :35000.0

JPA - Like Keyword

Like keyword is used with Where clause in a query to filter out records based on similar items.

Following the same example employee management used in previous chapters, we will go through the service classes using like keyword of JPQL.

Example - Usage of Like keyword using JPA

Create a class named LikeDemo.java under com.tutorialspoint.eclipselink.service package as follows−

LikeDemo.java

package com.tutorialspoint.eclipselink.service;

import java.util.List;

import com.tutorialspoint.eclipselink.entity.Employee;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;

public class LikeDemo {
   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager();

      //Like
      Query query = entitymanager.createQuery("Select e " + "from Employee e " + "where e.ename LIKE 'M%'");
      
      List<Employee> list1=(List<Employee>)query.getResultList( );
      
      for( Employee e:list1 ) {
         System.out.print("Employee ID :"+e.getEid( ));
         System.out.println("\t Employee name :"+e.getEname( ));
      }
   }
}

Output

Run the code as Java Application in Eclipse IDE.

After compilation and execution of the above program you will get following result on the console panel of eclipse IDE.

Employee ID :1202	 Employee name :Manisha
Employee ID :1203	 Employee name :Masthanvali

JPA - Order By Clause

Order By clause is used after Where clause in a query to order the records.

Following the same example employee management used in previous chapters, we will go through the service classes using order by clause of JPQL.

Example - Usage of Order By Clause using JPA

Create a class named OrderByDemo.java under com.tutorialspoint.eclipselink.service package as follows−

OrderByDemo.java

package com.tutorialspoint.eclipselink.service;

import java.util.List;

import com.tutorialspoint.eclipselink.entity.Employee;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;

public class OrderByDemo {
   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager();

      // Order By
      Query query = entitymanager.createQuery( "Select e " + "from Employee e " + "ORDER BY e.ename ASC" );

      List<Employee> list = (List<Employee>)query.getResultList( );

      for( Employee e:list ) {
         System.out.print("Employee ID :" + e.getEid( ));
         System.out.println("\t Employee Name :" + e.getEname( ));
      }
   }
}

Output

Run the code as Java Application in Eclipse IDE.

After compilation and execution of the above program you will get following result on the console panel of eclipse IDE.

Employee ID :1201	 Employee Name :Gopal
Employee ID :1206	 Employee Name :Kiran
Employee ID :1205	 Employee Name :Krishna
Employee ID :1202	 Employee Name :Manisha
Employee ID :1203	 Employee Name :Masthanvali
Employee ID :1204	 Employee Name :Satish

Example - Ordering in Descending Order using JPA

OrderByDemo.java

package com.tutorialspoint.eclipselink.service;

import java.util.List;

import com.tutorialspoint.eclipselink.entity.Employee;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;

public class OrderByDemo {
   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager();

      // Order By
      Query query = entitymanager.createQuery( "Select e " + "from Employee e " + "ORDER BY e.ename DESC" );

      List<Employee> list = (List<Employee>)query.getResultList( );

      for( Employee e:list ) {
         System.out.print("Employee ID :" + e.getEid( ));
         System.out.println("\t Employee Name :" + e.getEname( ));
      }
   }
}

Output

Run the code as Java Application in Eclipse IDE.

After compilation and execution of the above program you will get following result on the console panel of eclipse IDE.

Employee ID :1204	 Employee Name :Satish
Employee ID :1203	 Employee Name :Masthanvali
Employee ID :1202	 Employee Name :Manisha
Employee ID :1205	 Employee Name :Krishna
Employee ID :1206	 Employee Name :Kiran
Employee ID :1201	 Employee Name :Gopal

JPA - Named Query

A @NamedQuery annotation is defined as a query with a predefined unchangeable query string. Instead of dynamic queries, usage of named queries may improve code organization by separating the JPQL query strings from POJO. It also passes the query parameters rather than embedding literals dynamically into the query string and results in more efficient queries.

Example - Usage of Named Query in JPA

First of all, add NamedQuery annotation to the Employee entity class named Employee.java under com.tutorialspoint.eclipselink.entity package as follows−

Employee.java

package com.tutorialspoint.eclipselink.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.Table;

@Entity
@Table
@NamedQuery(query = "Select e from Employee e where e.eid = :id", name = "find employee by id")
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;
   }
   
   @Override
   public String toString() {
      return "Employee [eid=" + eid + ", ename=" + ename + ", salary=" + salary + ", deg=" + deg + "]";
   }
}

Create a class named NamedQueries.java under com.tutorialspoint.eclipselink.service package as follows −

NamedQueries.java

package com.tutorialspoint.eclipselink.service;

import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;
import com.tutorialspoint.eclipselink.entity.Employee;

public class NamedQueries {
   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager();
      Query query = entitymanager.createNamedQuery("find employee by id");
      
      query.setParameter("id", 1204);
      List<Employee> list = query.getResultList( );
      
      for( Employee e:list ){
         System.out.print("Employee ID :" + e.getEid( ));
         System.out.println("\t Employee Name :" + e.getEname( ));
      }
   }
}

Output

Run the code as Java Application in Eclipse IDE.

After compilation and execution of the above program you will get following result on the console panel of eclipse IDE.

Employee ID :1204	 Employee Name :Satish

JPA - Advanced Mappings

JPA is a library which is released with java specification. Therefore, it supports all object oriented concepts for entity persistence. Till now we are done with the basics of object relational mapping. This chapter takes you through the advanced mappings between objects and relational entities.

Inheritance Strategies

Inheritance is the core concept of object oriented language, therefore we can use inheritance relationships or strategies between entities. JPA support three types of inheritance strategies such as SINGLE_TABLE, JOINED_TABLE, and TABLE_PER_CONCRETE_CLASS.

Let us consider an example of Staff, TeachingStaff, NonTeachingStaff classes and their relationships as follows:

Inheritance Strategy

In the above shown diagram Staff is an entity and TeachingStaff and NonTeachingStaff are the sub entities of Staff.

In coming chapters, we're discussing all three strategies of inheritance.

JPA - Single Table Strategy

Overview

Single-Table strategy takes all classes fields (both super and sub classes) and map them down into a single table known as SINGLE_TABLE strategy. Here discriminator value plays key role in differentiating the values of three entities in one table.

Let us consider the above example, TeachingStaff and NonTeachingStaff are the sub classes of class Staff. Remind the concept of inheritance (is a mechanism of inheriting the properties of super class by sub class) and therefore sid, sname are the fields which belongs to both TeachingStaff and NonTeachingStaff. Create a JPA project. All the modules of this project as follows:

Creating Entities

Create a package named com.tutorialspoint.eclipselink.entity under src package if not present. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows:

Staff.java

package com.tutorialspoint.eclipselink.entity;

import java.io.Serializable;

import jakarta.persistence.DiscriminatorColumn;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Inheritance;
import jakarta.persistence.InheritanceType;
import jakarta.persistence.Table;

@Entity
@Table
@Inheritance( strategy = InheritanceType.SINGLE_TABLE )
@DiscriminatorColumn( name = "type" )

public class Staff implements Serializable {
   private static final long serialVersionUID = 1L;
   @Id
   @GeneratedValue( strategy = GenerationType.AUTO )
   
   private int sid;
   private String sname;
   
   public Staff( int sid, String sname ) {
      super( );
      this.sid = sid;
      this.sname = sname;
   }
   
   public Staff( ) {
      super( );
   }
   
   public int getSid( ) {
      return sid;
   }
   
   public void setSid( int sid ) {
      this.sid = sid;
   }
   
   public String getSname( ) {
      return sname;
   }
   
   public void setSname( String sname ) {
      this.sname = sname;
   }
}

In the above code @DescriminatorColumn specifies the field name (type) and the values of it shows the remaining (Teaching and NonTeachingStaff) fields.

Create a subclass (class) to Staff class named TeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The TeachingStaff Entity class is shown as follows:

TeachingStaff.java

package com.tutorialspoint.eclipselink.entity;

import jakarta.persistence.DiscriminatorValue;
import jakarta.persistence.Entity;

@Entity
@DiscriminatorValue( value="TS" )
public class TeachingStaff extends Staff {
   private static final long serialVersionUID = 1L;
   private String qualification;
   private String subjectexpertise;

   public TeachingStaff( int sid, String sname, 
   
   String qualification,String subjectexpertise ) {
      super( sid, sname );
      this.qualification = qualification;
      this.subjectexpertise = subjectexpertise;
   }

   public TeachingStaff( ) {
      super( );
   }

   public String getQualification( ){
      return qualification;
   }

   public void setQualification( String qualification ){
      this.qualification = qualification;
   }

   public String getSubjectexpertise( ) {
      return subjectexpertise;
   }

   public void setSubjectexpertise( String subjectexpertise ){
      this.subjectexpertise = subjectexpertise;
   }
}

Create a subclass (class) to Staff class named NonTeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The NonTeachingStaff Entity class is shown as follows:

NonTeachingStaff.java

package com.tutorialspoint.eclipselink.entity;

import jakarta.persistence.DiscriminatorValue;
import jakarta.persistence.Entity;

@Entity
@DiscriminatorValue( value = "NS" )

public class NonTeachingStaff extends Staff {
   private static final long serialVersionUID = 1L;
   private String areaexpertise;

   public NonTeachingStaff( int sid, String sname, String areaexpertise ) {
      super( sid, sname );
      this.areaexpertise = areaexpertise;
   }

   public NonTeachingStaff( ) {
      super( );
   }

   public String getAreaexpertise( ) {
      return areaexpertise;
   }

   public void setAreaexpertise( String areaexpertise ){
      this.areaexpertise = areaexpertise;
   }
}

Persistence.xml

Persistence.xml file contains the configuration information of database and registration information of entity classes. The xml file is shown as follows:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="3.0" xmlns="https://jakarta.ee/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd">
	<persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
	<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
	<class>com.tutorialspoint.eclipselink.entity.Staff</class>
	<class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class>
	<class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class>
      <properties>
         <property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/>
         <property name="jakarta.persistence.jdbc.user" value="guest"/>
         <property name="jakarta.persistence.jdbc.password" value="guest123"/>
         <property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
         <property name="eclipselink.logging.level" value="FINE"/>
         <property name="eclipselink.ddl-generation" value="create-tables"/>
      </properties>
	</persistence-unit>
</persistence>

Service class

Service classes are the implementation part of business component. Create a package under src package named com.tutorialspoint.eclipselink.service if not present.

Create a class named SaveClient.java under the given package to store Staff, TeachingStaff, and NonTeachingStaff class fields. The SaveClient class is shown as follows:

SaveClient.java

package com.tutorialspoint.eclipselink.service;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.NonTeachingStaff;
import com.tutorialspoint.eclipselink.entity.TeachingStaff;

public class SaveClient {

   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager( );
      entitymanager.getTransaction( ).begin( );

      //Teaching staff entity 
      TeachingStaff ts1=new TeachingStaff(1,"Gopal","MSc MEd","Maths");
      TeachingStaff ts2=new TeachingStaff(2, "Manisha", "BSc BEd", "English");
      
      //Non-Teaching Staff entity
      NonTeachingStaff nts1=new NonTeachingStaff(3, "Satish", "Accounts");
      NonTeachingStaff nts2=new NonTeachingStaff(4, "Krishna", "Office Admin");

      //storing all entities
      entitymanager.persist(ts1);
      entitymanager.persist(ts2);
      entitymanager.persist(nts1);
      entitymanager.persist(nts2);
      
      entitymanager.getTransaction().commit();
      
      entitymanager.close();
      emfactory.close();
   }
}

Output

After compilation and execution of the above program you will get notifications in the console panel of Eclipse IDE. Check MySQL workbench for output. The output in a tabular format is shown as follows:

Sid Type Sname Areaexpertise Qualification Subjectexpertise
1 TS Gopal   MSC MED Maths
2 TS Manisha   BSC BED English
3 NS Satish Accounts    
4 NS Krishna Office Admin    

Finally you will get single table which contains all three classs fields and differs with discriminator column named Type (field).

JPA - Joined Table Strategy

Overview

Joined table strategy is to share the referenced column which contains unique values to join the table and make easy transactions. Let us reconsider the example discussed in Joined Table Strategy chapter.

Create a JPA Project. All the project modules shown as follows:

Creating Entities

Create a package named com.tutorialspoint.eclipselink.entity under src package if not present. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows:

Staff.java

package com.tutorialspoint.eclipselink.entity;

import java.io.Serializable;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Inheritance;
import jakarta.persistence.InheritanceType;
import jakarta.persistence.Table;

@Entity
@Table
@Inheritance( strategy = InheritanceType.JOINED )
public class Staff implements Serializable {
   private static final long serialVersionUID = 1L;
   @Id
   @GeneratedValue( strategy = GenerationType.AUTO )
   
   private int sid;
   private String sname;
   
   public Staff( int sid, String sname ) {
      super( );
      this.sid = sid;
      this.sname = sname;
   }
   
   public Staff( ) {
      super( );
   }
   
   public int getSid( ) {
      return sid;
   }
   
   public void setSid( int sid ) {
      this.sid = sid;
   }
   
   public String getSname( ) {
      return sname;
   }
   
   public void setSname( String sname ) {
      this.sname = sname;
   }
}

Create a subclass (class) to Staff class named TeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The TeachingStaff Entity class is shown as follows:

TeachingStaff.java

package com.tutorialspoint.eclipselink.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.PrimaryKeyJoinColumn;

@Entity
@PrimaryKeyJoinColumn(referencedColumnName="sid")
public class TeachingStaff extends Staff {
   private static final long serialVersionUID = 1L;
   private String qualification;
   private String subjectexpertise;

   public TeachingStaff( int sid, String sname, 
   
   String qualification,String subjectexpertise ) {
      super( sid, sname );
      this.qualification = qualification;
      this.subjectexpertise = subjectexpertise;
   }

   public TeachingStaff( ) {
      super( );
   }

   public String getQualification( ){
      return qualification;
   }

   public void setQualification( String qualification ){
      this.qualification = qualification;
   }

   public String getSubjectexpertise( ) {
      return subjectexpertise;
   }

   public void setSubjectexpertise( String subjectexpertise ){
      this.subjectexpertise = subjectexpertise;
   }
}

Create a subclass (class) to Staff class named NonTeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The NonTeachingStaff Entity class is shown as follows:

NonTeachingStaff.java

package com.tutorialspoint.eclipselink.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.PrimaryKeyJoinColumn;

@Entity
@PrimaryKeyJoinColumn(referencedColumnName="sid")
public class NonTeachingStaff extends Staff {
   private static final long serialVersionUID = 1L;
   private String areaexpertise;

   public NonTeachingStaff( int sid, String sname, String areaexpertise ) {
      super( sid, sname );
      this.areaexpertise = areaexpertise;
   }

   public NonTeachingStaff( ) {
      super( );
   }

   public String getAreaexpertise( ) {
      return areaexpertise;
   }

   public void setAreaexpertise( String areaexpertise ) {
      this.areaexpertise = areaexpertise;
   }
}

Persistence.xml

Persistence.xml file contains the configuration information of database and registration information of entity classes. The xml file is shown as follows:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="3.0" xmlns="https://jakarta.ee/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd">
	<persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
	<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
	<class>com.tutorialspoint.eclipselink.entity.Staff</class>
	<class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class>
	<class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class>
      <properties>
         <property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/>
         <property name="jakarta.persistence.jdbc.user" value="guest"/>
         <property name="jakarta.persistence.jdbc.password" value="guest123"/>
         <property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
         <property name="eclipselink.logging.level" value="FINE"/>
         <property name="eclipselink.ddl-generation" value="create-tables"/>
      </properties>
	</persistence-unit>
</persistence>

Service class

Service classes are the implementation part of business component. Create a package under src package named com.tutorialspoint.eclipselink.service.

Create a class named SaveClient.java under the given package to store Staff, TeachingStaff, and NonTeachingStaff class fields. Then SaveClient class as follows:

SaveClient.java

package com.tutorialspoint.eclipselink.service;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.NonTeachingStaff;
import com.tutorialspoint.eclipselink.entity.TeachingStaff;

public class SaveClient {
   public static void main( String[ ] args ) {
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager( );
      entitymanager.getTransaction( ).begin( );

      //Teaching staff entity 
      TeachingStaff ts1 = new TeachingStaff(1,"Gopal","MSc MEd","Maths");
      TeachingStaff ts2 = new TeachingStaff(2, "Manisha", "BSc BEd", "English");
      
      //Non-Teaching Staff entity
      NonTeachingStaff nts1 = new NonTeachingStaff(3, "Satish", "Accounts");
      NonTeachingStaff nts2 = new NonTeachingStaff(4, "Krishna", "Office Admin");

      //storing all entities
      entitymanager.persist(ts1);
      entitymanager.persist(ts2);
      entitymanager.persist(nts1);
      entitymanager.persist(nts2);

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

Output

After compilation and execution of the above program you will get notifications in the console panel of Eclipse IDE. For output check MySQL workbench as follows:

Here three tables are created and the result of staff table in a tabular format is shown as follows:

Sid Dtype Sname
1 TeachingStaff Gopal
2 TeachingStaff Manisha
3 NonTeachingStaff Satish
4 NonTeachingStaff Krishna

The result of TeachingStaff table in a tabular format is shown as follows:

Sid Qualification Subjectexpertise
1 MSC MED Maths
2 BSC BED English

In the above table sid is the foreign key (reference field form staff table) The result of NonTeachingStaff table in tabular format is shown as follows:

Sid Areaexpertise
3 Accounts
4 Office Admin

Finally the three tables are created using their fields respectively and SID field is shared by all three tables. In staff table SID is primary key, in remaining (TeachingStaff and NonTeachingStaff) tables SID is foreign key.

JPA - Table Per Class Strategy

Overview

Table per class strategy is to create a table for each sub entity. The staff table will be created but it will contain null records. The field values of Staff table must be shared by TeachingStaff and NonTeachingStaff tables.Let us reconsider the example discussed in Joined Table Strategy chapter.

All modules of this project are shown as follows:

Creating Entities

Create a package named com.tutorialspoint.eclipselink.entity under src package if not present. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows:

Staff.java

package com.tutorialspoint.eclipselink.entity;

import java.io.Serializable;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Inheritance;
import jakarta.persistence.InheritanceType;
import jakarta.persistence.Table;

@Entity
@Table
@Inheritance( strategy = InheritanceType.TABLE_PER_CLASS )
public class Staff implements Serializable {
   private static final long serialVersionUID = 1L;
   @Id
   @GeneratedValue( strategy = GenerationType.AUTO )

   private int sid;
   private String sname;

   public Staff( int sid, String sname ) {
      super( );
      this.sid = sid;
      this.sname = sname;
   }

   public Staff( ) {
      super( );
   }

   public int getSid( ) {
      return sid;
   }

   public void setSid( int sid ) {
      this.sid = sid;
   }

   public String getSname( ) {
      return sname;
   }

   public void setSname( String sname ) {
      this.sname = sname;
   }
}

Create a subclass (class) to Staff class named TeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The TeachingStaff Entity class is shown as follows:

TeachingStaff.java

package com.tutorialspoint.eclipselink.entity;

import jakarta.persistence.Entity;

@Entity
public class TeachingStaff extends Staff {
   private static final long serialVersionUID = 1L;
   private String qualification;
   private String subjectexpertise;

   public TeachingStaff( int sid, String sname, String qualification, String subjectexpertise ) {
      super( sid, sname );
      this.qualification = qualification;
      this.subjectexpertise = subjectexpertise;
   }

   public TeachingStaff( ) {
      super( );
   }

   public String getQualification( ){
      return qualification;
   }
   
   public void setQualification( String qualification ) {
      this.qualification = qualification;
   }

   public String getSubjectexpertise( ) {
      return subjectexpertise;
   }

   public void setSubjectexpertise( String subjectexpertise ){
      this.subjectexpertise = subjectexpertise;
   }
}

Create a subclass (class) to Staff class named NonTeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The NonTeachingStaff Entity class is shown as follows:

NonTeachingStaff.java

package com.tutorialspoint.eclipselink.entity;

import jakarta.persistence.Entity;

@Entity
public class NonTeachingStaff extends Staff {
   private static final long serialVersionUID = 1L;
   private String areaexpertise;

   public NonTeachingStaff( int sid, String sname, String areaexpertise ) {
      super( sid, sname );
      this.areaexpertise = areaexpertise;
   }

   public NonTeachingStaff( ) {
      super( );
   }

   public String getAreaexpertise( ) {
      return areaexpertise;
   }

   public void setAreaexpertise( String areaexpertise ) {
      this.areaexpertise = areaexpertise;
   }
}

Persistence.xml

Persistence.xml file contains the configuration information of database and registration information of entity classes. The xml file is shown as follows:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="3.0" xmlns="https://jakarta.ee/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd">
	<persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
	<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
	<class>com.tutorialspoint.eclipselink.entity.Staff</class>
	<class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class>
	<class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class>
      <properties>
         <property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/>
         <property name="jakarta.persistence.jdbc.user" value="guest"/>
         <property name="jakarta.persistence.jdbc.password" value="guest123"/>
         <property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
         <property name="eclipselink.logging.level" value="FINE"/>
         <property name="eclipselink.ddl-generation" value="create-tables"/>
      </properties>
	</persistence-unit>
</persistence>

Service class

Service classes are the implementation part of business component. Create a package under src package named com.tutorialspoint.eclipselink.service.

Create a class named SaveClient.java under the given package to store Staff, TeachingStaff, and NonTeachingStaff class fields. The SaveClient class is shown as follows:

SaveClient.java

package com.tutorialspoint.eclipselink.service;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;

import com.tutorialspoint.eclipselink.entity.NonTeachingStaff;
import com.tutorialspoint.eclipselink.entity.TeachingStaff;

public class SaveClient {
   public static void main( String[ ] args ) {
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager( );
      entitymanager.getTransaction( ).begin( );

      //Teaching staff entity 
      TeachingStaff ts1 = new TeachingStaff(1,"Gopal","MSc MEd","Maths");
      TeachingStaff ts2 = new TeachingStaff(2, "Manisha", "BSc BEd", "English");
      
      //Non-Teaching Staff entity
      NonTeachingStaff nts1 = new NonTeachingStaff(3, "Satish", "Accounts");
      NonTeachingStaff nts2 = new NonTeachingStaff(4, "Krishna", "Office Admin");

      //storing all entities
      entitymanager.persist(ts1);
      entitymanager.persist(ts2);
      entitymanager.persist(nts1);
      entitymanager.persist(nts2);

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

Output

After compilation and execution of the above program you will get notifications in the console panel of Eclipse IDE. For output, check MySQL workbench as follows:

Here the three tables are created and the Staff table contains null records.

The result of TeachingStaff in a tabular format is shown as follows:

Sid Qualification Sname Subjectexpertise
1 MSC MED Gopal Maths
2 BSC BED Manisha English

The above table TeachingStaff contains fields of both Staff and TeachingStaff Entities.

The result of NonTeachingStaff in a tabular format is shown as follows:

Sid Areaexpertise Sname
3 Accounts Satish
4 Office Admin Krishna

The above table NonTeachingStaff contains fields of both Staff and NonTeachingStaff Entities.

JPA - Entity Relationships

Overview

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

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 applicable 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 applicable. 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

@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 linked 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.

@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.

@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.

JPA - @ManyToOne Relationships

Overview

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 applicable 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 applicable. 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

Creating Entities

Follow the above given diagram for creating entities. Create a package named com.tutorialspoin.eclipselink.entity under src package if not present. Create a class named Department.java under given package. The class Department entity is shown as follows:

Department.java

package com.tutorialspoint.eclipselink.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.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;
   }
}

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

Employee.java

package com.tutorialspoint.eclipselink.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.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 file is required to configure the database and the registration of entity classes.

The configuration details are user specifications. The persistence.xml file is shown as follows:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="3.0" xmlns="https://jakarta.ee/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd">
	<persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
	<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
	<class>com.tutorialspoint.eclipselink.entity.Employee</class>
	<class>com.tutorialspoint.eclipselink.entity.Department</class>
      <properties>
         <property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/>
         <property name="jakarta.persistence.jdbc.user" value="guest"/>
         <property name="jakarta.persistence.jdbc.password" value="guest123"/>
         <property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
         <property name="eclipselink.logging.level" value="FINE"/>
         <property name="eclipselink.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 initialization. Create a package under src package named com.tutorialspoint.eclipselink.service. The DAO class named ManyToOne.java is created under given package. The DAO class is shown as follows:

ManyToOne.java

package com.tutorialspoint.eclipselink.service;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;

import com.tutorialspoint.eclipselink.entity.Department;
import com.tutorialspoint.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();
   }
}

Output

After compilation and execution of the above program you will get notifications in the console panel of Eclipse 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 Wali	50000	101

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

JPA - @OneToMany Relationships

Overview

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 linked to 0, 1 or many rows in Table B.

Let us consider the example if Employee and Department is in a reverse unidirectional manner, relation is Many-To-One relation.

Creating Entities

Create a package named com.tutorialspoin.eclipselink.entity under src package if not present. Create a class named Department.java under given package. The class Department entity is shown as follows:

Department.java

package com.tutorialspoint.eclipselink.entity;

import java.util.List;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.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;
   }
}

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

Employee.java

package com.tutorialspoint.eclipselink.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.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 will be created by the eclipse 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="3.0" xmlns="https://jakarta.ee/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd">
	<persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
	<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
	<class>com.tutorialspoint.eclipselink.entity.Employee</class>
	<class>com.tutorialspoint.eclipselink.entity.Department</class>
      <properties>
         <property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/>
         <property name="jakarta.persistence.jdbc.user" value="guest"/>
         <property name="jakarta.persistence.jdbc.password" value="guest123"/>
         <property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
         <property name="eclipselink.logging.level" value="FINE"/>
         <property name="eclipselink.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 initialization. Create a package under src package named com.tutorialspoint.eclipselink.service. The DAO class named OneToMany.java is created under given package. The DAO class is shown as follows:

OneToMany.java

package com.tutorialspoint.eclipselink.service;

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

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;

import com.tutorialspoint.eclipselink.entity.Department;
import com.tutorialspoint.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();
   }
}

Output

After compilation and execution of the above program you will get notifications in the console panel of Eclipse 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_employee;

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	Masthanvali    50000

JPA - @OneToOne Relationships

Overview

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 example if Employee and Department is in a reverse unidirectional manner, relation is One-To-One relation.

Creating Entities

Create a package named com.tutorialspoin.eclipselink.entity under src package if not present. Create a class named Department.java under given package. The class Department entity is shown as follows:

Department.java

package com.tutorialspoint.eclipselink.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.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;
   }
}

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

Employee.java

package com.tutorialspoint.eclipselink.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.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 will be created by the eclipse 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="3.0" xmlns="https://jakarta.ee/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd">
	<persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
	<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
	<class>com.tutorialspoint.eclipselink.entity.Employee</class>
	<class>com.tutorialspoint.eclipselink.entity.Department</class>
      <properties>
         <property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/>
         <property name="jakarta.persistence.jdbc.user" value="guest"/>
         <property name="jakarta.persistence.jdbc.password" value="guest123"/>
         <property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
         <property name="eclipselink.logging.level" value="FINE"/>
         <property name="eclipselink.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 initialization. Create a package under src package named com.tutorialspoint.eclipselink.service. The DAO class named OneToOne.java is created under given package. The DAO class is shown as follows:

OneToOne.java

package com.tutorialspoint.eclipselink.service;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;

import com.tutorialspoint.eclipselink.entity.Department;
import com.tutorialspoint.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();
   }
}

Output

After compilation and execution of the above program you will get notifications in the console panel of Eclipse 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

JPA - @ManyToMany Relationships

Overview

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.

@ManyToOne Relation

Creating Entities

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

Clas.java

package com.tutorialspoint.eclipselink.entity;

import java.util.Set;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.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;
   }	  
}

Create the second entity in this relation Teacher entity class, named Teacher.java under com.tutorialspoint.eclipselink.entity package. The Teacher entity class is shown as follows:

Teacher.java

package com.tutorialspoint.eclipselink.entity;

import java.util.Set;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.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 will be created by the eclipse 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="3.0" xmlns="https://jakarta.ee/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd">
	<persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
	<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
	<class>com.tutorialspoint.eclipselink.entity.Clas</class>
	<class>com.tutorialspoint.eclipselink.entity.Teacher</class>
      <properties>
         <property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/>
         <property name="jakarta.persistence.jdbc.user" value="guest"/>
         <property name="jakarta.persistence.jdbc.password" value="guest123"/>
         <property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
         <property name="eclipselink.logging.level" value="FINE"/>
         <property name="eclipselink.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 initialization. Create a package under src package named com.tutorialspoint.eclipselink.service. The DAO class named ManyToMany.java is created under given package. The DAO class is shown as follows:

ManyToMany.java

package com.tutorialspoint.eclipselink.service;

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

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;

import com.tutorialspoint.eclipselink.entity.Clas;
import com.tutorialspoint.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( );
   }
}

Output

After compilation and execution of the above program you will get notifications in the console panel of Eclipse 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         Masthanvali

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