1. Hibernate JPA Introduction

1.1. Know Hibernate

Hibernate is an open source object-relational mapping framework, which makes a very lightweight object encapsulation of JDBC. It establishes a mapping relationship between POJOs and database tables. It is an automatic ORM framework, Hibernate can automatically generate SQL statements, automatically execute, Allows Java programmers to manipulate databases using object programming thinking at will.

1.2. Know about JPA

The full name of JPA: Java Persistence API, also known as Java Persistence API, is a set of ORM based specification launched by SUN Company, which is composed of a series of interfaces and abstract classes.

JPA uses JDK 5.0 annotations to describe object-relational table mappings and persist run-time entity objects to the database.

Disadvantage:

  • Because the persistence layer encapsulation is too complete, resulting in developers can not optimize SQL, can not flexibly use JDBC native SQL, Hibernate encapsulates JDBC, so direct access to the database is not as efficient as JDBC. Hibernate is not the best place to use database specific optimization mechanisms
  • The use of ORM principles in the framework resulted in overly complex configuration. In large projects, such as over 300 tables, the configuration files and contents were very large. In addition, dtos were flying around, resulting in performance and maintenance issues
  • Setting lazy to false in many places will result in slow data query and loading, especially for cascading queries.

Advantage:

  • Standardized JPA is one of the Java EE standards published by the JCP organization, so any framework that claims to conform to the JPA standard follows the same architecture and provides the same access API, which ensures that enterprise applications developed based on JPA can run under different JPA frameworks with minimal modifications.
  • Container-level transactions such as large data sets, transactions, and concurrency are supported in the JPA framework, which enables JPA to play a greater role in enterprise applications beyond the limitations of simple persistence frameworks.
  • Simplicity One of the main goals of JPA is to provide a simpler programming model: Creating entities in the JPA framework is as simple as creating Java classes. There are no restrictions or restrictions, only need to use javax.persistence.Entity annotation, JPA framework and interface are very simple, not too many special rules and design pattern requirements, developers can easily master. JPA is designed on a non-invasive basis so it can be easily integrated with other frameworks or containers
  • JPA’s query language is object-oriented rather than database-oriented, and it constructs query statements in object-oriented natural syntax, which can be regarded as the equivalent of Hibernate HQL. JPA defines the unique Java Persistence Query Language (JPQL), an extension of EJB QL, which is a Query Language for entities that operate on entities rather than tables in a relational database, It also supports advanced query features such as batch updates and modifications, joins, GROUP BY, and HAVING that are normally only available in SQL, and even supports subqueries.
  • Advanced features The ability to support advanced object-oriented features such as inheritance between classes, polymorphism, and complex relationships between classes in JPA enables developers to maximize the use of object-oriented models to design enterprise applications without having to deal with the persistence of these features in relational databases.

1.3 Relationship between JPA and Hibernate

The JPA specification is essentially an ORM specification, not an ORM framework, because JPA does not provide an ORM implementation. It just defines specifications and provides programming apis, but the implementation is provided by the service vendor

JPA schematic diagram:

The relationship between JPA and Hibernate is just like the relationship between JDBC and JDBC drivers. JPA is the specification, and Hibernate is also a JPA implementation in addition to being an ORM framework.

Can JPA replace Hibernate? Can the JDBC specification drive the underlying database? The answer is no, if you use the JPA specification for database operations, you need Hibernate as its implementation class at the bottom for data persistence.

2. Setting up the development environment (IDEA)

Let’s use Maven to create

2.1. Create maven project with IDEA (SRC /test/resources directory may not be available)

2.2. Import POM coordinates

Create /resources/ meta-INF /persistence. XML configuration file

  • Path: configure it to the meta-INF folder in the resources classpath with the file name: persistence.xml
  • Note: It is recommended to also set up meta-INF /persistence.xml under SRC /test/resources/ since the tests are mainly done under SRC /test/
  • Persistence Template: setting= “file and code Template=” JPA== “Deployment descriptors=” persistencexx.xml

Persistence. XML content:

<? The XML version = "1.0" encoding = "utf-8"? > < persistence XMLNS = "http://java.sun.com/xml/ns/persistence" version = "2.0" > <! -- name: persistent unit name, transaction-type: Persistence unit transaction type (JTA: distributed transaction,RESOURCE_LOCAL: local transaction) --> <persistence-unit name="myJpa" transaction-type="RESOURCE_LOCAL"> <! - the jpa implementation, configure jpa service providers - > < the provider > org. Hibernate. Jpa. HibernatePersistenceProvider < / provider > <! Provider provider provider provider provider provider provider provider provider provider provider --<class>com.caochenlei.hibernate.jpa.Customer</class>--> <! -- Optional configuration: Configure jPA implementer configuration information --> <properties> <! -- Database configuration: Database Driver, address database, database, database account password - > < property name = "hibernate. Connection. Driver_class" value = ". Com. Mysql. JDBC Driver "/ > < property Name = "hibernate. Connection. Url" value = "JDBC: mysql: / / 127.0.0.1:3306 / hibernate_jpa" / > < property name="hibernate.connection.username" value="root"/> <property name="hibernate.connection.password" value="password"/> <! <property name="hibernate.show_sql" value="true" /><! <property name="hibernate. format_SQL "value="true"/><! -- Format SQL --> <! None: no table is created create: the program creates a database table when it is running (if there is a table, delete the table before creating it) update: the program creates a table when it is running (if there is a table, the table is not created) create-drop: The table is generated from the Model class every time Hibernate is loaded, but the table is automatically dropped as soon as sessionFactory is closed. Validate: Each time Hibernate is loaded, verify that the database table structure is created, and only the tables in the database are compared. No new tables are created, but new values are inserted. --> <property name="hibernate.hbm2ddl.auto" value="update" /> </properties> </persistence-unit> </persistence>Copy the code

2.4. Write the mapping configuration between the entity class and the database table (the purpose is to operate on the entity class, as well as the database table)

@entity: declares the Entity class. @table: configures the mapping between the Entity class and the Table. Name: configures the name of the database Table. */ @data@entity@table (name = "tb_customer") public class Customer {/** * @id: Declare primary key configuration * @generatedValue: Configure primary key generation strategy * strategy: * generationType. IDENTITY: auto-increment, mysql * the underlying database must support auto-increment (the underlying database supports auto-increment for id) * generationType. SEQUENCE: Sequence, oracle * the underlying database must support sequence * generationType.table: Jpa provides a mechanism for primary key auto-increment in the form of a database table * generationType. AUTO: the program automatically helps us select primary key generation policies * @column: configure the mapping between attributes and fields * name: @id @GeneratedValue(Strategy = GenerationType.identity) @column (name = "Customer_id ") private Long Id; @id @generatedValue (Strategy = GenerationType.identity) @column (name =" Customer_id ") private Long Id; @column (name = "customer_name") private String name; @column (name="customer_age") private int age; @column (name="customer_sex") private Boolean sex; @column (name="customer_phone") private String phone; @column (name="customer_address") private String address; // Client address}Copy the code

Corresponding database table information:

2.5. Test the execution of the save operation

/** * Test jPA save * case: Save a customer to the database * JPA steps * 1 Load the configuration file create factory (Entity Manager factory) object * 2. Get the entity manager * 3 from the entity Manager factory. Get transaction object, start transaction * 4. Complete add, delete, change and query operation * 5. Commit transaction (rollback transaction) * 6. */ @test public void testSave() {//1. Loading the configuration file to create the factory (entity manager) factory object EntityManagerFactory factory = Persistence. CreateEntityManagerFactory (" myJpa "); / / 2. The entity manager accessed by the entity manager factory EntityManager em = factory. CreateEntityManager (); EntityTransaction tx = em.getTransaction(); tx.begin(); Customer Customer = new Customer(); customer.setName("Sam"); customer.setAddress("Beijing"); // save em.persist(customer); //5. Commit transaction tx.mit (); Em.close (); factory.close(); }Copy the code

2.6. View logs

Hibernate: 
    create table tb_customer (
       customer_id bigint not null auto_increment,
        customer_address varchar(255),
        customer_age integer,
        customer_name varchar(255),
        customer_phone varchar(255),
        customer_sex bit,
        primary key (customer_id)
    ) engine=InnoDB
Hibernate: 
    insert 
    into
        tb_customer
        (customer_address, customer_age, customer_name, customer_phone, customer_sex) 
    values
        (?, ?, ?, ?, ?)
Copy the code

2.7, you can see that the SQL statement is automatically generated for us, because the XML is set to update, so if there is a table, it will not regenerate into a table

<! None: no table is created create: the program creates a database table when it is running (if there is a table, delete the table before creating it) update: the program creates a table when it is running (if there is a table, the table is not created) create-drop: The table is generated from the Model class every time Hibernate is loaded, but the table is automatically dropped as soon as sessionFactory is closed. Validate: Each time Hibernate is loaded, verify that the database table structure is created, and only the tables in the database are compared. No new tables are created, but new values are inserted. --> <property name="hibernate.hbm2ddl.auto" value="update" />Copy the code

Setup complete!

Simple test:

The HQL statement is automatically generated

end~