JPA – Architecture

JPA – Architecture ”; Previous Next 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. 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. 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. Print Page Previous Next Advertisements ”;

JPA – Entity Managers

JPA – Entity Managers ”; Previous Next 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: 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: package com.tutorialspoint.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.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: <?xml version=”1.0″ encoding=”UTF-8″?> <persistence version=”2.0″ xmlns=”http://java.sun.com/xml/ns/persistence” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd”> <persistence-unit name=”Eclipselink_JPA” transaction-type=”RESOURCE_LOCAL”> <class>com.tutorialspoint.eclipselink.entity.Employee</class> <properties> <property name=”javax.persistence.jdbc.url” value=”jdbc:mysql://localhost:3306/jpadb”/> <property name=”javax.persistence.jdbc.user” value=”root”/> <property name=”javax.persistence.jdbc.password” value=”root”/> <property name=”javax.persistence.jdbc.driver” value=”com.mysql.jdbc.Driver”/> <property name=”eclipselink.logging.level” value=”FINE”/> <property name=”eclipselink.ddl-generation” value=”create-tables”/> </properties> </persistence-unit> </persistence> 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 as follows: Create Employee Creating an Employee class named as CreateEmployee.java as follows: package com.tutorialspoint.eclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.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. 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 Update Employee To Update an employee, we need to get record form database, make changes, and finally committ it. The class named UpdateEmployee.java is shown as follows: package com.tutorialspoint.eclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.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(); } } 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. 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. package com.tutorialspoint.eclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.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

JPA – Introduction

JPA – Introduction ”; Previous Next 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 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 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. Print Page Previous Next Advertisements ”;

JPA – Quick Guide

JPA – Quick Guide ”; Previous Next 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 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 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 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. 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. 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 maintaining data. The core part of this object relational technology is mapping orm.xml files. 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, the type of data, and its relations with self-entity or entities 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 Used by many professional programmers. ORM Architecture The ORM architecture looks as follows. 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 contains attributes such as ID, name, salary, and designation. It also contains methods like setter and getter of those attributes. Employee DAO/Service classes contain service methods such as

JPA – JPQL

JPA – JPQL ”; Previous Next 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: 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 won’t 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 Create a class named ScalarandAggregateFunctions.java under com.tutorialspoint.eclipselink.service package as follows. package com.tutorialspoint.eclipselink.service; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; public class ScalarandAggregateFunctions { 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); } //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); } } After compilation and execution of the above program you will get output in the console panel of Eclipse IDE as follows: Employee NAME :GOPAL Employee NAME :MANISHA Employee NAME :MASTHANVALI Employee NAME :SATISH Employee NAME :KRISHNA Employee NAME :KIRAN ax Employee Salary :40000.0 Between, And, Like Keywords ‘Between’, ‘And’, and ‘Like’ are the main keywords of JPQL. These keywords are used after Where clause in a query. Create a class named BetweenAndLikeFunctions.java under com.tutorialspoint.eclipselink.service package as follows: package com.tutorialspoint.eclipselink.service; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; import com.tutorialspoint.eclipselink.entity.Employee; public class BetweenAndLikeFunctions { 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( )); } //Like Query query1 = entitymanager.createQuery(“Select e ” + “from Employee e ” + “where e.ename LIKE ”M%””); List<Employee> list1=(List<Employee>)query1.getResultList( ); for( Employee e:list1 ) { System.out.print(“Employee ID :”+e.getEid( )); System.out.println(“t Employee name :”+e.getEname( )); } } } After compilation and execution of the above program you will get output in the console panel of Eclipse IDE as follows: 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 Employee ID :1202 Employee name :Manisha Employee ID :1203 Employee name :Masthanvali Ordering To Order the records in JPQL we use ORDER BY clause. The usage of this clause is same as the use in SQL, but it deals with entities. Follow the Order by example. Create a class Ordering.java under com.tutorialspoint.eclipselink.service package as follows: package com.tutorialspoint.eclipselink.service; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; import com.tutorialspoint.eclipselink.entity.Employee; public class Ordering { 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 ” + “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( )); } } } After compilation and execution of the above program you will get output in the console panel of Eclipse IDE as follows: 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 Named Queries 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. First of all, add @NamedQuery annotation to the Employee entity class named Employee.java under com.tutorialspoint.eclipselink.entity package as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.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

JPA – Advanced Mappings

JPA – Advanced Mappings ”; Previous Next 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: In the above shown diagram Staff is an entity and TeachingStaff and NonTeachingStaff are the sub entities of Staff. Here we will discuss the above example in all three strategies of inheritance. Single Table strategy 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. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows: package com.tutorialspoint.eclipselink.entity; import java.io.Serializable; import javax.persistence.DiscriminatorColumn; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; @Entity @Table @Inheritance( strategy = InheritanceType.SINGLE_TABLE ) @DiscriminatorColumn( name = “type” ) public class Staff implements Serializable { @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: package com.tutorialspoint.eclipselink.entity; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue( value=”TS” ) public class TeachingStaff extends Staff { 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: package com.tutorialspoint.eclipselink.entity; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue( value = “NS” ) public class NonTeachingStaff extends Staff { 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=”2.0″ xmlns=”http://java.sun.com/xml/ns/persistence” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd”> <persistence-unit name=”Eclipselink_JPA” transaction-type=”RESOURCE_LOCAL”> <class>com.tutorialspoint.eclipselink.entity.Staff</class> <class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class> <class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class> <properties> <property name=”javax.persistence.jdbc.url” value=”jdbc:mysql://localhost:3306/jpadb”/> <property name=”javax.persistence.jdbc.user” value=”root”/> <property name=”javax.persistence.jdbc.password” value=”root”/> <property name=”javax.persistence.jdbc.driver” value=”com.mysql.jdbc.Driver”/> <property name=”eclipselink.logging.level” value=”FINE”/> <property name=”eclipselink.ddl-generation” value=”create-tables”/> </properties> </persistence-unit> </persistence> 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: package com.tutorialspoint.eclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.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(); } } 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 class’s fields and differs with discriminator column named ‘Type’ (field). Joined table Strategy Joined table strategy is to share the referenced column which contains unique values to join the table and make easy transactions. Let us consider the same example as above. Create a JPA Project. All the project modules shown as follows: Creating Entities Create a package named ‘com.tutorialspoint.eclipselink.entity’ under ‘src’ package. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows: package com.tutorialspoint.eclipselink.entity; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; @Entity @Table @Inheritance( strategy = InheritanceType.JOINED ) public class Staff implements Serializable { @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( )

JPA – ORM Components

JPA – ORM Components ”; Previous Next 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. 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: 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: <? 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

JPA – Entity Relationships

JPA – Entity Relationships ”; Previous Next This chapter takes you through the relationships between Entities. Generally the relations are more effective between tables in the database. Here the entity classes are treated as relational tables (concept of JPA), therefore the relationships between Entity classes are as follows: @ManyToOne Relation @OneToMany Relation @OneToOne Relation @ManyToMany Relation @ManyToOne Relation Many-To-One relation between entities: Where one entity (column or set of columns) is/are referenced with another entity (column or set of columns) which contain unique values. In relational databases these relations are 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: Create a JPA project in eclipse IDE named JPA_Eclipselink_MTO. All the modules of this project are shown as follows: Creating Entities Follow the above given diagram for creating entities. Create a package named ‘com.tutorialspoin.eclipselink.entity’ under ‘src’ package. Create a class named Department.java under given package. The class Department entity is shown as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Department { @Id @GeneratedValue( strategy=GenerationType.AUTO ) private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName( ){ return name; } public void setName( String deptName ){ this.name = deptName; } } 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: package com.tutorialspoint.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity public class Employee{ @Id @GeneratedValue( strategy= GenerationType.AUTO ) private int eid; private String ename; private double salary; private String deg; @ManyToOne private Department department; public Employee(int eid, String ename, double salary, String deg) { super( ); this.eid = eid; this.ename = ename; this.salary = salary; this.deg = deg; } public Employee( ) { super(); } public int getEid( ) { return eid; } public void setEid(int eid) { this.eid = eid; } public String getEname( ) { return ename; } public void setEname(String ename) { this.ename = ename; } public double getSalary( ) { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDeg( ) { return deg; } public void setDeg(String deg) { this.deg = deg; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } } Persistence.xml Persistence.xml file is required to configure the database and the registration of entity classes. Persitence.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 = “2.0” xmlns = “http://java.sun.com/xml/ns/persistence” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd”> <persistence-unit name = “Eclipselink_JPA” transaction-type = “RESOURCE_LOCAL”> <class>com.tutorialspoint.eclipselink.entity.Employee</class> <class>com.tutorialspoint.eclipselink.entity.Department</class> <properties> <property name = “javax.persistence.jdbc.url” value = “jdbc:mysql://localhost:3306/jpadb”/> <property name = “javax.persistence.jdbc.user” value = “root”/> <property name = “javax.persistence.jdbc.password” value=”root”/> <property name = “javax.persistence.jdbc.driver” value=”com.mysql.jdbc.Driver”/> <property name = “eclipselink.logging.level” value = “FINE”/> <property name = “eclipselink.ddl-generation” value = “create-tables”/> </properties> </persistence-unit> </persistence> 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: package com.tutorialspointeclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.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(); } } 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. @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. Create a JPA project in eclipse IDE named JPA_Eclipselink_OTM. All the modules of this project are shown as follows: Creating Entities Follow the above given diagram for creating entities. Create a package named ‘com.tutorialspoin.eclipselink.entity’ under ‘src’ package. Create a class named Department.java under given package. The class Department entity is shown as follows: package com.tutorialspoint.eclipselink.entity; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class Department { @Id @GeneratedValue( strategy=GenerationType.AUTO ) private int id; private String name; @OneToMany( targetEntity=Employee.class ) private List employeelist; public int getId() {