JPA EntityManager –HibernateEntityManager

呼延弘方
2023-12-01

JPA EntityManager is at the core of Java Persistence API. Hibernate is the most widely used JPA implementation.

JPA EntityManager是Java Persistence API的核心。 Hibernate是使用最广泛的JPA实现。

JPA实体管理器 (JPA EntityManager)

  • 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是非常重要的工具。 ORM帮助用Java对象表示数据库关系。
  • ORM consists of two concepts object-oriented and relational programming.

    ORM由面向对象和关系编程两个概念组成。
  • Hibernate is an ORM framework where programmer describes the way objects are represented in database. Hibernate handles the conversion automatically.

    Hibernate是一个ORM框架,程序员在其中描述对象在数据库中的表示方式。 Hibernate自动处理转换。
  • Hibernate provides implementation of JPA interfaces EntityManagerFactory and EntityManager.

    Hibernate提供了JPA接口EntityManagerFactoryEntityManager
  • 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.

    EntityManagerFactory提供EntityManager实例以连接到相同的数据库。 所有实例均配置为使用与默认实现定义的设置相同的设置。 可以准备几个实体管理器工厂以连接到不同的数据存储。
  • 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用于访问特定应用程序中的数据库。 它用于管理持久实体实例,通过其主键标识查找实体以及查询所有实体。

JPA EntityManager方法 (JPA EntityManager Methods)

JPA EntityManager is supported by the following set of methods. For better readability, I have not mentioned method arguments.

以下方法集支持JPA EntityManager。 为了提高可读性,我没有提到方法参数。

  1. persist – Make an instance managed and persistent.

    持久–将实例设为托管和持久。
  2. merge – Merge the state of the given entity into the current persistence context.

    合并–将给定实体的状态合并到当前的持久性上下文中。
  3. remove – Remove the entity instance.

    remove –删除实体实例。
  4. 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.

    查找-通过主键查找。 搜索指定类和主键的实体。 如果实体实例包含在持久性上下文中,则从那里返回它。
  5. getReference – returns and instance which is lazily fetched and will throw EntityNotFoundException when the instance is accessed for the first time.

    getReference –返回和延迟获取的实例,并且在首次访问该实例时将抛出EntityNotFoundException。
  6. flush – Synchronizes the persistence context with the database.

    flush –将持久性上下文与数据库同步。
  7. setFlushMode – set the flush mode for all the objects of the persistence context.

    setFlushMode –为持久性上下文的所有对象设置刷新模式。
  8. getFlushMode – get the flush mode for all the objects of the persistence context.

    getFlushMode –获取持久性上下文中所有对象的刷新模式。
  9. lock – Lock an entity instance that is contained in the persistence context with the specified lock mode type.

    lock –使用指定的锁定模式类型锁定持久性上下文中包含的实体实例。
  10. refresh – it refreshes the state of the instance from the database also it will overwrite the changes to the entity.

    refresh –刷新数据库中实例的状态,还将覆盖对实体的更改。
  11. 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.

    clear –清除持久性上下文,导致所有受管实体分离。 对尚未刷新到数据库的实体所做的更改将不会保留。
  12. detach – this is similar to the clear method, only addition is the entity which previously referenced the detached object will continue to do so.

    detach –这类似于clear方法,只是前面引用了分离对象的实体将继续这样做。
  13. contains – it checks if the managed entity belongs to the current persistence context.

    包含–检查受管实体是否属于当前持久性上下文。
  14. getLockMode – get the current lock mode for entity instance.

    getLockMode –获取实体实例的当前锁定模式。
  15. setProperty – set an entity manager property or hint.

    setProperty –设置实体管理器属性或提示。
  16. getProperties – get the properties and hints associated with the entity manager.

    getProperties –获取与实体管理器关联的属性和提示。
  17. createQuery – Create an instance of Query for executing a Java Persistence query language statement.

    createQuery –创建用于执行Java Persistence查询语言语句的Query实例。
  18. createNamedQuery – Create an instance of Query for executing a Java Persistence named query language statement.

    createNamedQuery –创建用于执行Java Persistence命名查询语言语句的Query实例。
  19. createNativeQuery – Create an instance of Query for executing a native sql statement.

    createNativeQuery –创建用于执行本机sql语句的Query实例。
  20. createNamedStoredProcedureQuery – Create an instance of StoredProcedureQuery for executing a stored procedure in the database.

    createNamedStoredProcedureQuery –创建StoredProcedureQuery的实例以在数据库中执行存储过程。
  21. createStoredProcedureQuery – Create an instance of StoredProcedureQuery for executing a stored procedure in the database.

    createStoredProcedureQuery –创建StoredProcedureQuery的实例以在数据库中执行存储过程。
  22. 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.

    joinTransaction –向实体管理器指示JTA事务处于活动状态。 应该在活动事务范围之外创建的JTA应用程序管理的实体管理器上调用此方法,以将其与当前JTA事务相关联。
  23. isJoinedToTransaction – it determines if the entityManager is linked to the current transaction.

    isJoinedToTransaction –确定entityManager是否链接到当前事务。
  24. unwrap – Return an object of the specified type to allow access to the provider-specific API

    展开–返回指定类型的对象,以允许访问提供程序特定的API
  25. getDelegate – return the provider object for the entityManager.

    getDelegate –返回entityManager的提供程序对象。
  26. close – close an application-managed entityManager.

    close –关闭应用程序管理的entityManager。
  27. isOpen – determine if the entityManager is open.

    isOpen –确定entityManager是否打开。
  28. getTransaction – Return the resource-level EntityTransaction object.

    getTransaction –返回资源级的EntityTransaction对象。
  29. getEntityManagerFactory – provides the entity manager factory for the entity manager.

    getEntityManagerFactory –为实体管理器提供实体管理器工厂。
  30. getCriteriaBuilder – Return an instance of CriteriaBuilder for the creation of CriteriaQuery objects.

    getCriteriaBuilder –返回CriteriaBuilder的实例以创建CriteriaQuery对象。
  31. getMetamodel – Return an instance of Metamodel interface for access to the metamodel of the persistence unit.

    getMetamodel –返回用于访问持久性单元的元模型的元模型接口的实例。
  32. createEntityGraph – Return a mutable EntityGraph that can be used to dynamically create an EntityGraph.

    createEntityGraph –返回可用于动态创建EntityGraph的可变EntityGraph。
  33. getEntityGraph – returns a named entityGraph

    getEntityGraph –返回一个命名的EntityGraph

Let’s look at some of the methods through EntityManager example project.

让我们看一下EntityManager示例项目中的一些方法。

Hibernate EntityManager示例 (Hibernate EntityManager Example)

We will create a maven project for JPA Hibernate EntityManager example, below image illustrates different component of our Eclipse project.

我们将为JPA Hibernate EntityManager示例创建一个maven项目,下图说明了Eclipse项目的不同组件。

I am using MySQL for database, below query will create our test table.

我正在使用MySQL作为数据库,下面的查询将创建我们的测试表。

CREATE TABLE `employee` (
  `employee_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `employee_name` varchar(32) NOT NULL DEFAULT '',
  PRIMARY KEY (`employee_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

It’s a very simple table but suits for our example to showcase EntityManager usage.

这是一个非常简单的表,但适合我们的示例来展示EntityManager的用法。

HibernateMaven依赖关系 (Hibernate Maven Dependencies)

We will have to include Hibernate and MySQL java driver dependencies in our pom.xml file. I am using Hibernate 5 with latest version of mysql-connector-java jar.

我们必须在pom.xml文件中包含Hibernate和MySQL Java驱动程序依赖项。 我正在将Hibernate 5与最新版本的mysql-connector-java jar一起使用。

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.journaldev.hibernate</groupId>
	<artifactId>hibernate-entitymanager</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>hibernate-entitymanager</name>
	<url>https://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<!-- MySQL connector -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.5</version>
		</dependency>
		<!-- Hibernate 5.2.6 Final -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.6.Final</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<sourceDirectory>src/main/java</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Hibernate的persistence.xml (Hibernate persistence.xml)

The most important part of using hibernate is to provide persistence.xml file. This xml holds the configuration for connecting to database.

使用Hibernate的最重要部分是提供persistence.xml文件。 该xml包含用于连接数据库的配置。

<persistence xmlns="https://xmlns.jcp.org/xml/ns/persistence"
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/persistence
             https://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
	version="2.1">

	<persistence-unit name="persistence">
		<description>Hibernate Entity Manager Example</description>
		<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

		<properties>
			<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="journaldev" />
			<property name="javax.persistence.jdbc.password" value="journaldev" />
			<property name="hibernate.show_sql" value="true" />
		</properties>

	</persistence-unit>

</persistence>
  • hibernate.show_sql is used to tell hibernate to print sql queries into log files or console.

    hibernate.show_sql用于告诉hibernate将sql查询打印到日志文件或控制台中。
  • 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.

    最重要的配置是provider类,即
    org.hibernate.jpa.HibernatePersistenceProvider 。 这就是Hibernate如何挂接到我们的应用程序中以用作JPA实现的方式。
  • 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.

    重要的是要注意,如从项目映像中所见,应该将persistence.xml放置在META-INF目录中。

Hibernate实体Bean (Hibernate Entity Bean)

We will now create an Employee.java class that will correspond to the employee table created in the database. The employee class is declared as entity using the @Entity annotation.

现在,我们将创建一个Employee.java类,该类与数据库中创建的employee表相对应。 使用@Entity 批注将employee类声明为实体。

package com.journaldev.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;

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

	private String name;

	@Id
	@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) {
		this.name = name;
	}

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

}

Now it’s time to create our main program and run some queries using EntityManager methods.

现在是时候创建我们的主程序并使用EntityManager方法运行一些查询了。

package com.journaldev.jpa.hibernate.main;

import java.util.List;

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

import com.journaldev.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");
		entityManager.getTransaction().begin();
		Employee employee = new Employee();
		employee.setName("Pankaj");
		System.out.println("Saving Employee to Database");

		entityManager.persist(employee);
		entityManager.getTransaction().commit();
		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
		@SuppressWarnings("unchecked")
		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
		entityManager.getTransaction().begin();
		System.out.println("Deleting Employee with ID = " + emp.getEmployeeId());
		entityManager.remove(emp);
		entityManager.getTransaction().commit();

		// close the entity manager
		entityManager.close();
		entityManagerFactory.close();

	}
}
  1. Persistence.createEntityManagerFactory will provide EntityManagerFactory instance using the persistence-unit that we have provided in the persistence.xml file

    Persistence.createEntityManagerFactory将使用我们在persistence.xml文件中提供的persistence-unit提供EntityManagerFactory实例。
  2. entityManagerFactory.createEntityManager() will create EntityManager instance for us to use. Every time we call createEntityManager() method, it will return a new instance of EntityManager.

    entityManagerFactory.createEntityManager()将创建EntityManager实例供我们使用。 每次我们调用createEntityManager()方法时,它将返回一个EntityManager的新实例。
  3. entityManager.getTransaction().begin() method first pulls the transaction from current persistence context and then begins the transaction using begin() method.

    entityManager.getTransaction().begin()方法首先从当前持久性上下文中拉出事务,然后使用begin()方法开始事务。
  4. entityManager.persist(employee) is used to persist the employee object in the database.

    entityManager.persist(employee)用于将雇员对象保留在数据库中。
  5. entityManager.getTransaction.commit() method is used to fetch the transaction and then to commit the same transaction. This will commit all the changes to database.

    entityManager.getTransaction.commit()方法用于获取事务,然后提交同一事务。 这会将所有更改提交到数据库。
  6. entityManager.find() is used to find an entity in the database using primary key.

    entityManager.find()用于使用主键在数据库中查找实体。
  7. If you want to write a custom query, we can use entityManager.createQuery() method for it. Important point to note here is that the createQuery() method will have name given in the entity class and not the actual table name.

    如果您想编写一个自定义查询,我们可以为其使用entityManager.createQuery()方法。 这里要注意的重要一点是,createQuery()方法将具有在实体类中给定的名称,而不是实际的表名。
  8. entityManager.remove() should be used only when we have to remove an entity from the database.

    仅当我们必须从数据库中删除实体时,才应使用entityManager.remove()
  9. entityManager.close() is used to close the entity manager. Similarly entityManagerFactory.close() is to close the EntityManagerFactory. We should close these resources as soon as we are done with them.

    entityManager.close()用于关闭实体管理器。 同样, entityManagerFactory.close()将关闭EntityManagerFactory 。 一旦完成处理,我们应立即关闭这些资源。

Below is the output produced from one sample run of above program.

下面是上述程序的一个示例运行产生的输出。

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=?

Notice how the employee id is generated when it’s saved into database and then mapped back to the object. Also notice the sql queries getting printed into console. Note that Hibernate will create more logs but I haven’t put them here for maintaining readability.

请注意,将员工ID保存到数据库中后如何将其映射回该对象。 还请注意,SQL查询已打印到控制台中。 请注意,Hibernate将创建更多日志,但是为了保持可读性,我没有将它们放在此处。

That’s all for JPA EntityManager and it’s example with hibernate implementation. You can download the final Hibernate EntityManager example project from below link.

这就是JPA EntityManager的全部内容,并且是使用hibernate实现的示例。 您可以从下面的链接下载最终的Hibernate EntityManager示例项目。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/17379/jpa-entitymanager-hibernate

 类似资料:

相关阅读

相关文章

相关问答