Introduction and use of ORM - JPA

ORM overview

ORM (object relational mapping) represents object relational mapping. In object-oriented software development, objects can be mapped to relational database through orm. As long as a set of program can establish the association between the object and the database, the operating object can directly operate the database data. It can be said that this set of program realizes the ORM object relationship mapping

In short: ORM is to establish the relationship between entity classes and database tables, so as to achieve the purpose that operating entity classes is equivalent to operating database tables.

Why use ORM

When implementing an application (without O/R Mapping), we may write code of special multiple data access layers to save data, modify data and delete data from the database, and these codes are repeated. Using ORM will greatly reduce repetitive code. Object Relational Mapping (ORM) mainly realizes the mapping from program objects to relational database data.

Common ORM framework

Common orm frameworks: Mybatis (ibatis), Hibernate, spring data JPA

Overview of hibernate and JPA

hibernate overview

Hibernate is an open source object relational mapping framework. It encapsulates JDBC with very lightweight objects. It establishes a mapping relationship between POJO and database tables. It is a fully automatic orm framework. Hibernate can automatically generate and execute SQL statements, so that Java programmers can use object programming thinking to manipulate the database at will.

JPA overview

The full name of JPA is Java Persistence API, that is, Java Persistence API. It is a set of ORM based specifications launched by SUN company. It is internally composed of a series of interfaces and abstract classes.

JPA describes the mapping relationship between object and relational table through JDK 5.0 annotation, and persists the entity object at run time to the database.

Advantages of JPA

1. Standardization

JPA is one of the Java EE standards released by JCP organization. Therefore, any framework claiming to comply with 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 a small amount of modifications.

2. Support of container level features

JPA framework supports container level transactions such as large data sets, transactions and concurrency, which makes JPA go beyond the limitations of simple persistence framework and play a greater role in enterprise applications.

3. Simple and convenient

One of the main goals of JPA is to provide a simpler programming model: creating entities under the JPA framework is as simple as creating Java classes without any constraints and restrictions. Only javax.persistence.Entity needs to be used for annotation. The JPA framework and interface are also very simple without many special rules and design pattern requirements, which can be easily mastered by developers. JPA is designed based on non intrusive principles, so it can be easily integrated with other frameworks or containers

4. Query capability

JPA's query language is object-oriented rather than database oriented. It constructs query statements with object-oriented natural syntax, which can be regarded as the equivalent of Hibernate HQL. JPA defines a unique JPQL (Java Persistence Query Language). JPQL is an extension of EJB QL. It is a query language for entities. The operation object is entities rather than tables in relational databases. It can support batch update and modification, JOIN, GROUP BY, HAVING and other advanced query features that are usually provided only by SQL, It can even support subqueries.

5. Advanced features

JPA can support advanced object-oriented features, such as inheritance between classes, polymorphism and complex relationships between classes. This support can enable developers to design enterprise applications by using object-oriented model to the greatest extent without dealing with the persistence of these features in relational database.

Relationship between JPA and hibernate

JPA specification is essentially an ORM specification. Note that it is not an ORM framework - because JPA does not provide ORM implementation, it only formulates some specifications and provides some programming API interfaces, but the specific implementation is provided by the service manufacturer.

The relationship between JPA and Hibernate is like the relationship between JDBC and jdbc driver. JPA is a specification. Hibernate is also a JPA implementation in addition to being an ORM framework. How does JPA replace Hibernate? Can the JDBC specification drive the underlying database? The answer is no, that is, if the JPA specification is used for database operation, the underlying layer needs hibernate as its implementation class to complete data persistence.

Use of JPA

Introduction to development package

Since JPA is an API specification formulated by sun company, we do not need to import additional JPA related jar packages, but only the jar packages of JPA providers. We choose Hibernate as the JPA provider, so we need to import Hibernate related jar packages.

Download website: http://sourceforge.net/projects/hibernate/files/hibernate-orm/5.0.7.Final/

Construction of development environment

l import jar package from traditional project

l maven project import coordinates

<properties>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	<project.hibernate.version>5.0.7.Final</project.hibernate.version>
</properties>

<dependencies>
	<!-- junit -->
	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.12</version>
		<scope>test</scope>
	</dependency>

	<!-- hibernate yes jpa Support package for -->
	<dependency>
		<groupId>org.hibernate</groupId>
		<artifactId>hibernate-entitymanager</artifactId>
		<version>${project.hibernate.version}</version>
	</dependency>

	<!-- c3p0 -->
	<dependency>
		<groupId>org.hibernate</groupId>
		<artifactId>hibernate-c3p0</artifactId>
		<version>${project.hibernate.version}</version>
	</dependency>

	<!-- log journal -->
	<dependency>
		<groupId>log4j</groupId>
		<artifactId>log4j</artifactId>
		<version>1.2.17</version>
	</dependency>

	<!-- Mysql and MariaDB -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.6</version>
	</dependency>
</dependencies>

Description of common notes

@Entity
	Role: Specifies that the current class is an entity class.
@Table
	Role: Specifies the correspondence between entity classes and tables.
	Properties:
		name :  Specifies the name of the database table
@Id
	Function: Specifies that the current field is the primary key.
@GeneratedValue
	Function: Specifies the generation method of the primary key..
	Properties:
		strategy : Specifies the primary key generation policy.
@Column
	Role: specify the correspondence between entity class attributes and database tables
	Properties:
		name: Specifies the column name of the database table.
		unique: Is it unique  
		nullable: Can it be blank  
		inserttable: Can I insert  
		updateable: Can I update  
		columnDefinition: Define how to create this column when creating a table DDL  
		secondaryTable: From table name. If this column is not built on the master table (it is built on the master table by default), this attribute defines the name of the slave table where the column is located to build the development environment[a key]

Configure the core configuration file of JPA

Create a folder named META-INF under the src path of the java project, and create a configuration file named persistence.xml under this folder

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
  <!--Configuration required persistence-unit node
      Persistence unit:
          name: Persistence unit name
          transaction-type: Ways of transaction management
                  JTA: Distributed transaction management
                  RESOURCE_LOCAL: Local transaction management
  -->
  <persistence-unit name="myJpa" transaction-type="RESOURCE_LOCAL">
    <!--jpa Implementation of -->
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

    <!--Optional configuration: Configuration jpa Configuration information of implementer-->
    <properties>
      <!-- database information 
          user name, javax.persistence.jdbc.user
          password,  javax.persistence.jdbc.password
          Drive,  javax.persistence.jdbc.driver
          Database address   javax.persistence.jdbc.url
      -->
      <property name="javax.persistence.jdbc.user" value="root"/>
      <property name="javax.persistence.jdbc.password" value="1234"/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql:///spring"/>

      <!--to configure jpa Implementer(hibernate)Configuration information for
          display sql           :    false|true
          Automatically create database tables    :   hibernate.hbm2ddl.auto
                  create      : Create database tables when the program is running (if there are tables, delete the tables first and then create them)
                  update      : Create tables when the program runs (if there are tables, they will not be created)
                  none        : No tables will be created
      -->
      <property name="hibernate.show_sql" value="true" />
      <property name="hibernate.hbm2ddl.auto" value="update" />
    </properties>
  </persistence-unit>
</persistence>

Primary key generation strategy in JPA

For mapping hibernate entities through annotation, the hibernate primary key based on annotation is identified as @ id, and its generation rule is set by @ GeneratedValue. Here @ id and @ GeneratedValue are standard usage of JPA.

The four standard usages provided by JPA are table, sequence, identity and auto.

IDENTITY: the primary key is automatically generated by the database (mainly automatic growth type)

SEQUENCE: generate the primary key according to the SEQUENCE of the underlying database, provided that the database supports the SEQUENCE.

AUTO: the primary key is controlled by the program

TABLE: use a specific database TABLE to save the primary key

Introduction to JPA API

Persistence object

The Persistence object is mainly used to obtain the EntityManagerFactory object. By calling the createEntityManagerFactory static method of this class, an EntityManagerFactory is created according to the Persistence unit name in the configuration file.

EntityManagerFactory

The EntityManagerFactory interface is mainly used to create EntityManager instances

Because EntityManagerFactory is a thread safe object (that is, there will be no thread safety problem when multiple threads access the same EntityManagerFactory object), and the creation of EntityManagerFactory is extremely wasteful of resources, we can optimize the creation of EntityManagerFactory when programming with JPA, Only one EntityManagerFactory exists in one project

EntityManager

In the JPA specification, EntityManager is the core object to complete the persistence operation. As a normal java object, an entity class will become a persistent object only after calling EntityManager to persist it. EntityManager objects manage O/R mappings between a set of entity classes and underlying data sources. It can be used to manage and update entity beans, find entity beans based on the primary key, and query entities through JPQL statements.

We can call the EntityManager method to obtain transactions and persist the database

Method description:

getTransaction : Get transaction object
persist :  Save operation
merge :  update operation
remove :  Delete operation
find/getReference :  according to id query

EntityTransaction

In the JPA specification, EntityTransaction is the core object to complete transaction operations. The functions undertaken by EntityTransaction in our java code are relatively simple

Method description:

begin: Open transaction
commit: Commit transaction
rollback: Rollback transaction

Complex query in JPA

JPQL full name Java Persistence Query Language

Based on the EJB query language (EJB QL) first introduced in EJB 2.0, Java persistent query language (JPQL) is a portable query language. It aims to bind SQL syntax and simple query semantics with the expression of object-oriented expression language. The query written in this language is portable and can be compiled into SQL on all mainstream database servers.

Its features are similar to native SQL statements and are completely object-oriented, accessed through class names and attributes, rather than table names and table attributes.

Tags: Framework

Posted on Tue, 30 Nov 2021 23:26:15 -0500 by hayson1991