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实现。
EntityManagerFactory
and EntityManager
. Hibernate提供了JPA接口EntityManagerFactory
和EntityManager
。 JPA EntityManager is supported by the following set of methods. For better readability, I have not mentioned method arguments.
以下方法集支持JPA EntityManager。 为了提高可读性,我没有提到方法参数。
Let’s look at some of the methods through EntityManager example project.
让我们看一下EntityManager示例项目中的一些方法。
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的用法。
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>
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查询打印到日志文件或控制台中。 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实现的方式。 persistence.xml
should be placed in the META-INF directory, as you can see from the project image. 重要的是要注意,如从项目映像中所见,应该将persistence.xml
放置在META-INF目录中。 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();
}
}
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实例。 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的新实例。 entityManager.getTransaction().begin()
method first pulls the transaction from current persistence context and then begins the transaction using begin() method. entityManager.getTransaction().begin()
方法首先从当前持久性上下文中拉出事务,然后使用begin()方法开始事务。 entityManager.persist(employee)
is used to persist the employee object in the database. entityManager.persist(employee)
用于将雇员对象保留在数据库中。 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()
方法用于获取事务,然后提交同一事务。 这会将所有更改提交到数据库。 entityManager.find()
is used to find an entity in the database using primary key. entityManager.find()
用于使用主键在数据库中查找实体。 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()方法将具有在实体类中给定的名称,而不是实际的表名。 entityManager.remove()
should be used only when we have to remove an entity from the database. 仅当我们必须从数据库中删除实体时,才应使用entityManager.remove()
。 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