JPA EntityManagerは、Java Persistence APIの中心に位置しています。Hibernateは、最も広く使われているJPAの実装です。


  • One of the most important aspect of a program is connection with database. Database connection and transaction with database is considered as most expensive transaction. ORM is a very important tool in this regard. ORM helps in representing relations of database in terms of java objects.
  • ORM consists of two concepts object-oriented and relational programming.
  • Hibernate is an ORM framework where programmer describes the way objects are represented in database. Hibernate handles the conversion automatically.
  • Hibernate provides implementation of JPA interfaces EntityManagerFactory and EntityManager.
  • EntityManagerFactory provides instances of EntityManager for connecting to same database. All the instances are configured to use the same setting as defined by the default implementation. Several entity manager factories can be prepared for connecting to different data stores.
  • JPA EntityManager is used to access a database in a particular application. It is used to manage persistent entity instances, to find entities by their primary key identity, and to query over all entities.


JPA EntityManagerは、以下の一連のメソッドでサポートされています。読みやすさのために、メソッドの引数は省略しています。

    1. persist – Make an instance managed and persistent.


    1. merge – Merge the state of the given entity into the current persistence context.


    1. remove – Remove the entity instance.


    1. find – Find by primary key. Search for an entity of the specified class and primary key. If the entity instance is contained in the persistence context, it is returned from there.


    1. getReference – returns and instance which is lazily fetched and will throw EntityNotFoundException when the instance is accessed for the first time.


    1. flush – Synchronizes the persistence context with the database.


    1. setFlushMode – set the flush mode for all the objects of the persistence context.


    1. getFlushMode – get the flush mode for all the objects of the persistence context.


    1. lock – Lock an entity instance that is contained in the persistence context with the specified lock mode type.


    1. refresh – it refreshes the state of the instance from the database also it will overwrite the changes to the entity.


    1. clear – Clear the persistence context, causing all managed entities to become detached. Changes made to entities that have not been flushed to the database will not be persisted.


    1. detach – this is similar to the clear method, only addition is the entity which previously referenced the detached object will continue to do so.


    1. contains – it checks if the managed entity belongs to the current persistence context.


    1. getLockMode – get the current lock mode for entity instance.


    1. setProperty – set an entity manager property or hint.


    1. getProperties – get the properties and hints associated with the entity manager.


    1. createQuery – Create an instance of Query for executing a Java Persistence query language statement.


    1. createNamedQuery – Create an instance of Query for executing a Java Persistence named query language statement.


    1. createNativeQuery – Create an instance of Query for executing a native sql statement.


    1. createNamedStoredProcedureQuery – Create an instance of StoredProcedureQuery for executing a stored procedure in the database.


    1. createStoredProcedureQuery – Create an instance of StoredProcedureQuery for executing a stored procedure in the database.


    1. joinTransaction – Indicate to the entity manager that a JTA transaction is active. This method should be called on a JTA application managed entity manager that was created outside the scope of the active transaction to associate it with the current JTA transaction.


    1. isJoinedToTransaction – it determines if the entityManager is linked to the current transaction.


    1. unwrap – Return an object of the specified type to allow access to the provider-specific API


    1. getDelegate – return the provider object for the entityManager.


    1. close – close an application-managed entityManager.


    1. isOpen – determine if the entityManager is open.


    1. getTransaction – Return the resource-level EntityTransaction object.


    1. getEntityManagerFactory – provides the entity manager factory for the entity manager.


    1. getCriteriaBuilder – Return an instance of CriteriaBuilder for the creation of CriteriaQuery objects.


    1. getMetamodel – Return an instance of Metamodel interface for access to the metamodel of the persistence unit.


    1. createEntityGraph – Return a mutable EntityGraph that can be used to dynamically create an EntityGraph.


    getEntityGraph – returns a named entityGraph



JPA EntityManager, Hibernate EntityManager example
CREATE TABLE `employee` (
  `employee_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `employee_name` varchar(32) NOT NULL DEFAULT '',
  PRIMARY KEY (`employee_id`)



私たちはpom.xmlファイルにHibernateとMySQLのJavaドライバの依存関係を含める必要があります。私は最新のmysql-connector-javaのjarを使用してHibernate 5を利用しています。

<project xmlns="" xmlns:xsi=""




		<!-- MySQL connector -->
		<!-- Hibernate 5.2.6 Final -->




<persistence xmlns=""

	<persistence-unit name="persistence">
		<description>Hibernate Entity Manager Example</description>

			<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
			<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/Test" />
			<property name="javax.persistence.jdbc.user" value="scdev" />
			<property name="javax.persistence.jdbc.password" value="scdev" />
			<property name="hibernate.show_sql" value="true" />


  • hibernate.show_sql is used to tell hibernate to print sql queries into log files or console.
  • The most important configuration is provider class i.e. org.hibernate.jpa.HibernatePersistenceProvider. This is how Hibernate is hooked into our application to be used as JPA implementation.
  • There are properties to connect to your database and driver to use.
  • It is important to note that persistence.xml should be placed in the META-INF directory, as you can see from the project image.



package com.scdev.jpa.hibernate.model;

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

@Table(name = "employee")
public class Employee {
	private int employeeId;

	private String name;

	@Column(name = "employee_id")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public int getEmployeeId() {
		return employeeId;

	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;

	@Column(name = "employee_name")
	public String getName() {
		return name;

	public void setName(String name) { = name;

	public String toString() {
		return "Employee [employeeId=" + employeeId + ", name=" + name + "]";



package com.scdev.jpa.hibernate.main;

import java.util.List;

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

import com.scdev.jpa.hibernate.model.Employee;

public class App {
	public static void main(String[] args) {
		EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("persistence");
		EntityManager entityManager = entityManagerFactory.createEntityManager();

		System.out.println("Starting Transaction");
		Employee employee = new Employee();
		System.out.println("Saving Employee to Database");

		System.out.println("Generated Employee ID = " + employee.getEmployeeId());

		// get an object using primary key.
		Employee emp = entityManager.find(Employee.class, employee.getEmployeeId());
		System.out.println("got object " + emp.getName() + " " + emp.getEmployeeId());

		// get all the objects from Employee table
		List<Employee> listEmployee = entityManager.createQuery("SELECT e FROM Employee e").getResultList();

		if (listEmployee == null) {
			System.out.println("No employee found . ");
		} else {
			for (Employee empl : listEmployee) {
				System.out.println("Employee name= " + empl.getName() + ", Employee id " + empl.getEmployeeId());
		// remove and entity
		System.out.println("Deleting Employee with ID = " + emp.getEmployeeId());

		// close the entity manager

    1. Persistence.createEntityManagerFactoryは、persistence.xmlファイルで提供されたpersistence-unitを使用してEntityManagerFactoryインスタンスを提供します。


    1. entityManagerFactory.createEntityManager()は、私たちが使用するためのEntityManagerインスタンスを作成します。createEntityManager()メソッドを呼び出すたびに、新しいEntityManagerインスタンスが返されます。


    1. entityManager.getTransaction().begin()メソッドは、最初に現在の永続化コンテキストからトランザクションを取得し、begin()メソッドを使用してトランザクションを開始します。


    1. entityManager.persist(employee)は、データベースにemployeeオブジェクトを永続化するために使用されます。


    1. entityManager.getTransaction().commit()メソッドは、トランザクションを取得し、同じトランザクションをコミットするために使用されます。これにより、すべての変更がデータベースにコミットされます。


    1. entityManager.find()は、主キーを使用してデータベース内のエンティティを検索するために使用されます。


    1. カスタムクエリを書きたい場合は、entityManager.createQuery()メソッドを使用することができます。ここで重要なポイントは、createQuery()メソッドにはエンティティクラスに指定された名前があることです。実際のテーブル名ではありません。


    1. entityManager.remove()は、データベースからエンティティを削除する必要がある場合にのみ使用する必要があります。




Starting Transaction
Saving Employee to Database
Hibernate: insert into employee (employee_name) values (?)
Generated Employee ID = 11
got object Pankaj 11
Dec 07, 2017 1:05:23 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select employee0_.employee_id as employee1_0_, employee0_.employee_name as employee2_0_ from employee employee0_
Employee name= Test, Employee id 5
Employee name= Pankaj, Employee id 6
Employee name= Pankaj, Employee id 11
Deleting Employee with ID = 11
Hibernate: delete from employee where employee_id=?

データベースに保存される際に従業員IDが生成され、それがオブジェクトにマッピングされることに注目してください。また、コンソールに表示されるSQLクエリにも注目してください。Hibernateはさらにログを生成しますが、可読性を保つため、ここでは省略しています。これがJPA EntityManagerとそのHibernate実装の例です。最終的なHibernate EntityManagerの例プロジェクトは以下のリンクからダウンロードできます。

「JPA Hibernate EntityManagerのサンプルプロジェクトをダウンロードする」


コメントを残す 0

Your email address will not be published. Required fields are marked *