Home Hibernate JPA Architecture and java persistence with example

JPA Architecture and java persistence with example

1. JPA Architecture :

Jpa architecture

1.1. Entity

  • An entity is a persistence domain object. Each Entity represents a table in a relational database, and each entity instance corresponds to a row in that table.
  • JPA uses Annotations or XML to map entities to a Relational database.
  • The persistent state of an entity fields or properties (setter and getter methods) use object/relational mapping annotations to map the entities and entity relationships to the relational data in the underlying data store.

Following image illustrates entity and relational data base table relation.

JPA entity

Following is the example for Student entity :

@Entity(name="STUDENT")
public class Student {
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO, generator="native")
	@GenericGenerator(name = "native", strategy = "native")
	@Column(name = "ID")
	private Long studentId;
	
	@Column(name = "FNAME")
	private String firstName;
	
	@Column(name = "LNAME")
	private String lastName;
	
	@Column(name = "CONTACT_NO")
	private String contactNo;
  
        // getters and setters

1.2. Persistence Unit:

  • A persistence unit defines a set of all entity classes that are managed by EntityManager instances in an application.
  • This set of entity classes represents the data contained within a single data store.
  • Persistence units are defined by the persistence.xml configuration file.
  • JPA uses the persistence.xml file to create the connection and setup the required environment. Provides information which is necessary for making database connections.

Example persistence unit configuration in persistence.xml :

<persistence-unit name="jbd-pu">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="password"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa_JBD"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
            
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect"/>
            <property name="hibernate.show_sql" value="true"/>
        </properties>
</persistence-unit>

1.3. Persistence Class:

  • Persistence (javax.persistence.Persistence) class contains java static methods to get EntityManagerFactory instances.
  • Since JPA 2.1 you can generatedatabase schemas and/or tables and/or create DDL scripts as determined by the supplied properties.

1.4. EntityManagerFactory :

  • EntityManagerFactory (javax.persistence.EntityManagerFactory) class is a factory for EntityManagers.
  • During the application startup time EntityManagerFactory is created with the help of Persistence-Unit.
  • Typically, EntityManagerFactory is created once (One EntityManagerfactory object per Database) and kept alive for later use.

Example to create EntityManagerFactory :

// jbd-pu is the persistence unit configured in persistence.xmpl
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jbd-pu");

1.5. EntityManager:

EntityManager is an interface to perform main actual database interactions.

  1. Creates persistence instance.
  2. Removes persistence instance.
  3. Finds entities by entity’s primary key.
  4. Allows queries to be run on entities.
  • Persistence Context : A persistence context handles a set of entities which hold data to be persisted in some persistence store (e.g. database).
  • Each EntityManager instance is associated with a PersistenceContext.

Example to create EntityManager :

EntityManagerFactory emf = Persistence.createEntityManagerFactory("jbd-pu");
EntityManager entityManager = emf.createEntityManager();

1.6. EntityTransaction :

  • A transaction is a set of operations that either fail or succeed as a unit.
  • A database transaction consists of a set of SQL operations that are committed or rolled back as a single unit
  • Any kind of modifications initiated via EntityManager object are placed within a transaction. An EntityManager object helps creating an EntityTransaction

Following is the example to create EntityTransaction :

EntityManagerFactory emf = Persistence.createEntityManagerFactory("jbd-pu");
EntityManager entityManager = emf.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();

1.7. Example to save student data into data base

public class App {
	
	public static void main(String[] args) {
		
		EntityManagerFactory emf = null;
		EntityManager entityManager = null;
		EntityTransaction transaction = null;

		try {
			emf = Persistence.createEntityManagerFactory("jbd-pu");
			entityManager = emf.createEntityManager();
			transaction = entityManager.getTransaction();
			transaction.begin();

			Student student = new Student();
			student.setFirstName("Roland");
			student.setLastName("Mark");
			student.setContactNo("+1-408-575-1317");

			entityManager.persist(student);

			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
		} finally {
			entityManager.close();
			emf.close();
		}
	}
}

1.8. Query :

Query is an interface and used to control query execution. An EntityManager object helps creating a Query object, the implementation depends on persistence provider.

Following is example to run query and get results :

Query query = entityManager.createQuery("SELECT s FROM STUDENT s");
List<Student> s = query.getResultList();
s.forEach(student-> System.out.println(student.getFirstName()));

1.9. Criteria Api

Criteria API, which supports to build SQL queries using java objects, so that with the JPA criteria API it’s possible to have type safe queries that can be checked at compile time.

Following is the example to demonstrates get results from DB using Criteria.

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Student> query = cb.createQuery(Student.class);//create query object
Root<Student> studentRoot = query.from(Student.class);//get object representing 'from' part
query.select(studentRoot);// combine 'select' and 'from' parts, equivalent to 'SELECT s FROM Student s;'
TypedQuery<Student> typedQuery = entityManager.createQuery(query);

typedQuery.getResultList()
	  .forEach(s->System.out.println(s.getFirstName()));
Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Follow him on LinkedIn or Twitter or Facebook

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay in Touch

Categories