1. JPA understanding
JPA is the abbreviation of Java Persistence API. It is a Java EE 5.0 platform standard open source object relationship mapping (ORM) specification developed by Sun company on the basis of fully absorbing the existing ORM framework (Hibernate).
The relationship between Hibernate and JPA:
Hibernate is an open-source object relational mapping (ORM) framework. It encapsulates JDBC with very lightweight objects. It establishes the mapping relationship between POJO and database tables. It is a fully automatic ORM framework. Hibernate can automatically generate SQL statements and execute them. Java programmers can use object-oriented thinking to manipulate the database at will.
JPA is the Java persistence specification officially proposed by Sun, and JPA is developed on the basis of fully absorbing the ORM frameworks such as Hibernate and TopLink.
In conclusion, JPA is a persistent relational mapping specification and interface API, while Hibernate is its implementation.
1.1. Advantages and disadvantages of JPA
Advantage:
① The operation code is very simple: insert persist, modify merge, query find, delete remove;
② Direct operation for persistent objects;
③ It provides world-class data cache, including first level cache, second level cache and query cache;
④ It has strong portability to switch databases, and extracts a dialect configuration interface corresponding to various databases. To change a database, you only need to modify the dialect configuration, drive the jar package, and connect the database.
Disadvantages:
① Cannot interfere with SQL statement generation;
② JPA is not suitable for projects with high efficiency requirements of SQL optimization;
③ JPA is also not suitable for large-scale projects with a data volume of over 100 million.
2. Create a JPA project of Hello World manually
2.1. jar package required for importing JPA project
Hibernate can be downloaded on the official website: http://hibernate.org/orm/releases/
Here, as an example of learning to use the version jar package of Hibernate 4.3.8, JPA 2.1, to build the project jar package:
There are three types of Hibernate jar packages needed to import the project:
① Required jar package for Hibernate:
Directory path location: hibernate-release-4.3.8.Final\lib\required
Import the jar package set as shown in the figure below:
② You also need to import the jar package supported by JPA. The directory path is: hibernate-release-4.3.8.Final\lib\jpa connects with Mysql database to drive the jar package;
2.2. Configure the core configuration file persistence.xml
The configuration file must be placed in the resources\META-INF directory of the classpath directory of the project (required by JPA specification);
The specific configuration of the persistence.xml file is as follows:
<persistence 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" version="2.0"> <!--Persistence unit name: Corresponding to project name--> <persistence-unit name="cn.yif.jpa01" transaction-type="RESOURCE_LOCAL"> <properties> <!-- Four connection database properties must be configured: configuration information can be found in project/etc/hibernate.properties Find in --> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" /> <property name="hibernate.connection.url" value="jdbc:mysql:///jpa01_0307" /> <property name="hibernate.connection.username" value="root" /> <property name="hibernate.connection.password" value="admin" /> <!-- 1 database dialect property must be configured --> <!-- Implement cross database key classes :query MySQLDialect Of getLimitString Method --> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" /> <!-- Optional configuration --> <!-- Generate table automatically --> <property name="hibernate.hbm2ddl.auto" value="create" /> <!-- Whether to display sql --> <property name="hibernate.show_sql" value="true" /> <!-- Format sql --> <property name="hibernate.format_sql" value="true" /> </properties> </persistence-unit> </persistence>
2.3. Create persistent Domain class Employee
package cn.yif.domain; import javax.persistence.*; //@Entity Indicates that the class is created by jpa Managed persistent objects, corresponding to a table in the database @Entity //@Table Represents the table name of the corresponding database @Table(name = "t_employee") public class Employee { //@Id Is a required annotation, indicating the primary key of the corresponding database @Id //@GeneratedValue Generation strategy of primary key,Most of them use AUTO //@GeneratedValue Do not configure by default AUTO @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; //@Column Indicates that if the database column name is inconsistent with the property name, it needs to be configured @Column(name = "e_name") private String name; @Column(name = "e_age") private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
2.4. Create Junit4 test class code
import cn.yif.domain.Employee; import org.junit.Test; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; public class JPAHelloTest { @Test public void testInsertEmpByJPA(){ Employee employee = new Employee(); employee.setName("Gao Wei Xiang"); employee.setAge(34); // Corresponding to the persistence-unit name="cn.yif.jpa01" // Create an entity class management factory through persistent classes EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("cn.yif.jpa01"); //Create an entity management class to implement CRUD EntityManager entityManager = entityManagerFactory.createEntityManager(); //from entityManager To open a transaction EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); //Persistent operation CRUD Write in persist entityManager.persist(employee); // Submission of affairs transaction.commit(); //close resource entityManager.close(); entityManagerFactory.close(); } }
Through the above steps, JPA can automatically create a t employee table and insert a piece of data in the created jpa01 0307 database:
3. Complete JPA CRUD process
3.1. Extract JPAUtil class
package cn.yif.utils; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; /** * Tool class: Singleton mode / static singleton mode static method */ public class JPAUtil { // Privatize this constructor,Don't let anyone else create this class private JPAUtil(){} // Physical management plant // Be careful:EntityManagerFactory This class is thread safe private static EntityManagerFactory entityManagerFactory; /** * Static code block. When the class is loaded, the code inside will be executed only once */ static{ try { entityManagerFactory = Persistence.createEntityManagerFactory("cn.yif.jpa01"); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Get EntityManagerFactory Error in runtime:"+e.getMessage()); } } // Get one. EntityManager object // Every time EntityManager All need to be recreated(EntityManager Not thread safe, recreate every time) public static EntityManager getEntityManager(){ return entityManagerFactory.createEntityManager(); } public static void close(EntityManager entityManager){ //close resource entityManager.close(); entityManagerFactory.close(); } }
4. hibernate.hbm2ddl.auto attribute value configuration in persistence.xml
As mentioned above, there are four configurations for the value value value of the hibernate.hbm2ddl.auto attribute: create drop, create, update, and validate. The following explains the differences and functions of these four different configuration scenarios:
① create-drop
Create drop function: first delete the table, create the table, and then delete the table;
Note: the entityManagerFactory.close() code must be executed before the table can be deleted and the drop table function can be executed
② create
Create function: delete the table first, and then create the table.
③ update
update function:
If there is no current JPA persistent table in the database, create the table according to the latest mapping;
If the database already has a table, no structure of the original table will be deleted, only columns will be added;
Note that if there is no such attribute in the table and there is one in the mapping information domain class, this attribute will be added
④ validate
validate function:
If the table in the database does not exist or the attribute in the domain class is larger than the field in the database table, an exception will be thrown;
The mapping information domain class will be verified with the corresponding fields in the database table. If the mapping is one-to-one or smaller than the fields in the database table, no exception will be thrown
5. Single table mapping configuration details
5.1. Configuration details of persistent domain mapping
5.1.1. Date and time type format
① Date and time format configuration
Use @ Temporal annotation to configure:
@Temporal(TemporalType.TIMESTAMP)
The default configuration will set the time format of the database table to: "yyyy MM DD HH: mm: SS“
@Temporal(TemporalType.DATE)
The time format of the database table will be set to: "yyyy MM DD"“
@Temporal(TemporalType.TIME)
The time format of the database table will be set to: "hh:mm:ss"
Persistent class domain configuration
@Temporal(TemporalType.TIMESTAMP) private Date createTime; // Creation time: format--"yyyy-MM-dd hh:mm:ss"(year--month--day--Time--branch--Second) @Temporal(TemporalType.DATE) private Date brithday; // Birthday: format--"yyyy-MM-dd"(year--month--Day) @Temporal(TemporalType.TIME) private Date classTime; // Class time: format--"hh:mm:ss""(Time--branch--Second)
The specific setting format is as follows:
5.1.2. Text length and long text type
If the length of the domain class corresponding to the length of the common table is not configured, the length of the default vachar field type in the database table will be given to 255, which takes up more space. We can specify a fixed length value through JPA annotation configuration.
Common String property field length configuration:
@Column(name = "t_name", length = 20)
@Column(name = "pwd", length = 100)
Add length configuration to @ Column annotation to specify the length of varchar field in database table;
Long text type property field configuration:
Add @ Lob annotation to the attribute of the corresponding domain class, and the corresponding field will be set to the type of longtext in the database, which can store large text.
Persistent class domain configuration
@Lob // Set to long text type private String Intro; // Profile: long text type
5.1.3. Attribute constraint settings
Non empty constraint:
Configure @ Column(nullable = false)
Unique constraint:
Configure @ Column(unique = true)
5.1.4. Other mapping configurations
① Temporary attribute configuration: Transient (temporary attribute - this attribute exists on the persistent object, but will not be written to the database);
@Transient private String temp;
② Set whether the table can be updated: @ Column(updatable=false), which means that it will be added when adding, but it cannot be modified when modifying (it's OK to understand, not generally);
③ Set whether the table can be added: @ Column(insertable=false), which means that the operation cannot be performed when adding, but the operation can be modified when modifying (it's OK to understand, not generally);
④ Custom persistent class domain attribute rule: @ Column(columnDefinition = "int check (age > 18)"), which is not supported by Mysql, but supported by Oracle (just understand, Mysql database can't be used)