Practical series (4) | Detailed explanation of JPA, including detailed code


JPA (Java Persistence API) is part of the Java EE specification, which defines a set of standard APIs for mapping Java objects to relational database tables. The goal of JPA is to simplify enterprise application development and make it easier for developers to implement mapping relationships between objects and database tables. The following are some basic concepts of JPA, supported databases, advantages and disadvantages, as well as specific application scenarios and case codes:
Insert image description here

1. Concepts and principles:

JPA mainly includes the following concepts:

  • Entity: The mapping of a specific thing in the real world in the database. Entity classes need to inherit java.io.Serializablethe interface and use JPA annotations to describe the mapping relationship with the database table.
  • Persistence: The process of mapping entity objects to database tables and saving their state in the database.
  • Persistence Management: Responsible for managing the mapping relationship between entity objects and database tables and the persistence operations of entity objects.
  • Query: JPA provides a standard query language (JPQL) for writing type-safe query statements. In addition, we can also use the Criteria API to write more flexible query conditions.

2. Supported databases:

JPA itself does not rely on a specific database, but supports different types of databases through various ORM (Object Relational Mapping) implementations. Common JPA ORM implementations are:

  • Hibernate: supports a variety of databases, such as MySQL, PostgreSQL, Oracle, SQL Server, etc.
  • EclipseLink: supports a variety of databases, such as MySQL, PostgreSQL, Oracle, SQL Server, etc.
  • OpenJPA: supports a variety of databases, such as MySQL, PostgreSQL, Oracle, SQL Server, etc.

3. Advantages and Disadvantages:

advantage:

  • Simplifies the mapping relationship between Java objects and database tables, reducing development difficulty.
  • Supports multiple databases and has good portability.
  • Provides a rich query language and query methods to facilitate developers to write complex queries.
    shortcoming:
  • The learning cost is high and you need to master a series of JPA annotations and APIs.
  • In some scenarios, JPA's query performance may not be as good as native SQL queries.

4. Application scenarios:

JPA is suitable for the following scenarios:

  • Enterprise-level application development: JPA can simplify the mapping relationship between objects and database tables and reduce development difficulty.
  • Web application development: JPA can be easily integrated into Web development frameworks such as Spring Boot to improve development efficiency.
  • Database migration: JPA supports a variety of databases and can be migrated between different databases.

5. Main methods:

JPA (Java Persistence API) is a standard specification for persisting Java objects to relational databases. JPA provides a set of APIs for defining entity classes, data access, and queries. Here are some of JPA's main methods, including specific code examples:

  1. Entity class related methods:
  • Entity: JPA entity class, used to map database tables.
  • @EntityAnnotation: Mark a class as a JPA entity class.
  • @TableNote: Specify the database table name corresponding to the entity class.
  • @IdAnnotation: Mark the primary key attribute of the entity class.
  • @GeneratedValueNote: Specify the primary key generation strategy.
  • @ColumnNote: Specify the database column corresponding to the entity class attribute.
@Entity  
@Table(name = "user")  
public class User {
    
      
   @Id  
   @GeneratedValue(strategy = GenerationType.IDENTITY)  
   private Long id;
   @Column(name = "email")  
   private String email;
   @Column(name = "last_name")  
   private String lastName;
   // 省略 getter 和 setter 方法  
}
  1. Data access related methods:
  • EntityManager: The data access interface provided by JPA is used to perform CRUD (create, read, update, delete) operations.
  • getEntityManager(): Get EntityManagerthe instance.
  • findAll(): Query all records.
  • findById(Long id): Query records based on ID.
  • save(User user): Save an entity object to the database.
  • deleteById(Long id): Delete the record with the specified ID.
@Repository  
public interface UserRepository extends JpaRepository<User, Long> {
    
      
}
  1. Query related methods:
  • CriteriaBuilder: The query builder provided by JPA, used to build JPQL (Java Persistence Query Language) queries.
  • CriteriaQuery: JPA query interface, used to write JPQL queries.
  • Root: The root object of JPQL query, used to represent entity classes.
  • Predicate: Predicate of JPQL query, used to express query conditions.
  • createQuery(Query query): Generate query objects based on the given JPQL query.
@Repository  
public interface UserRepository extends JpaRepository<User, Long> {
    
      
   @Query("select u from User u where u.email =?1 and u.lastName =?2")  
   List<User> findByEmailAddressAndLastName(String email, String lastName);  
}
  1. JPQL query:
  • JPQL is a query language provided by JPA for writing type-safe queries.
  • JPQL queries can be used with CriteriaBuilder and CriteriaQuery, or written directly in Java code.
@Repository  
public interface UserRepository extends JpaRepository<User, Long> {
    
      
   @Query("select u from User u where u.email =?1 and u.lastName =?2")  
   List<User> findByEmailAddressAndLastName(String email, String lastName);
   // 使用 CriteriaBuilder 和 CriteriaQuery 进行查询  
   @Query(value = "select u from User u where u.email =?1 and u.lastName =?2", nativeQuery = true)  
   List<User> findByEmailAddressAndLastName2(String email, String lastName);  
}

The above are some of the main methods of JPA. By using these methods and JPQL queries, we can implement complex queries and operations on the database. In actual projects, we can also use frameworks such as Spring Data JPA to further simplify the use of JPA.

6. The method description contains code:

JPA (Java Persistence API) is a standard specification for persisting Java objects to relational databases. The following lists some common uses of JPA and provides detailed code examples.

  1. Entity class mapping:
    First, you need to create an entity class for mapping database tables. For example, the following code creates an Userentity class named for use with the mapping usertable:
import javax.persistence.*;
@Entity  
@Table(name = "user")  
public class User {
    
      
   @Id  
   @GeneratedValue(strategy = GenerationType.IDENTITY)  
   private Long id;
   @Column(name = "email")  
   private String email;
   @Column(name = "last_name")  
   private String lastName;
   // 省略 getter 和 setter 方法  
}
  1. Entity class association: Associations between entity classes can be achieved
    using annotations such as @OneToOne, @OneToMany, @ManyToOneand . @ManyToManyFor example, the following code represents a one-to-one relationship between Userand :Address
import javax.persistence.*;
@Entity  
public class User {
    
      
   //...
   @OneToOne  
   @JoinColumn(name = "address_id")  
   private Address address;
   // 省略 getter 和 setter 方法  
}
  1. Query: CRUD operations can be performed
    using EntityManagerthe interface. For example, the following code queries all Userentities:
import javax.persistence.EntityManager;  
import javax.persistence.PersistenceContext;  
import java.util.List;
public class UserRepository {
    
      
   @PersistenceContext  
   private EntityManager entityManager;
   public List<User> findAll() {
    
      
       return entityManager.createQuery("SELECT u FROM User u", User.class).getResultList();  
   }  
}
  1. Query example:
    Write a query using JPQL (Java Persistence Query Language). For example, the following code queries all users who are 26 years or older:
import javax.persistence.EntityManager;  
import javax.persistence.PersistenceContext;  
import java.util.List;
public class UserRepository {
    
      
   @PersistenceContext  
   private EntityManager entityManager;
   public List<User> findUsersByAge() {
    
      
       String queryString = "SELECT u FROM User u WHERE u.age >= 26";  
       return entityManager.createQuery(queryString, User.class).getResultList();  
   }  
}
  1. Transaction support: Transactions can be supported
    using @Transactionalannotations. For example, the following code performs insert and query operations in one transaction:
import org.springframework.transaction.annotation.Transactional;
@Service  
public class UserService {
    
      
   @Autowired  
   private UserRepository userRepository;
   @Transactional  
   public void insertUser(User user) {
    
      
       userRepository.save(user);  
       userRepository.findUsersByAge();  
   }  
}

The above are some common uses of JPA. In actual projects, corresponding adjustments can be made according to specific needs.

7. Case code:

Suppose we want to develop a simple user management system that can use JPA for data persistence and query.
First, create a User entity class:

import javax.persistence.*;
@Entity  
public class User {
    
      
   @Id  
   @GeneratedValue(strategy = GenerationType.IDENTITY)  
   private Long id;
   @Column(nullable = false, unique = true)  
   private String username;
   @Column(nullable = false)  
   private String password;
   // 省略 getter 和 setter 方法  
}

Next, create a UserRepository interface for persistence operations:

import javax.persistence.EntityManager;  
import javax.persistence.PersistenceContext;  
import java.util.List;
public interface UserRepository {
    
      
   EntityManager getEntityManager();
   List<User> findAll();
   User findById(Long id);
   void save(User user);
   void deleteById(Long id);  
}

In actual projects, we can integrate this interface into Spring Boot and enable the persistence function through @SpringBootApplicationthe annotation function. Next, we use JPQL to query:@EnablePersistence

import javax.persistence.criteria.CriteriaBuilder;  
import javax.persistence.criteria.CriteriaQuery;  
import javax.persistence.criteria.Predicate;  
import javax.persistence.criteria.Root;
public class UserService {
    
      
   public List<User> findByUsername(String username) {
    
      
       CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();  
       CriteriaQuery<User> query = cb.createQuery(User.class);  
       Root<User> user = query.from(User.class);  
       Predicate predicate = cb.equal(user.get("username"), username);  
       query.where(predicate);  
       return getEntityManager().createQuery(query).getResultList();  
   }  
}

Finally, we can use this interface in the controller to perform data addition, deletion, modification and query operations:

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController  
@RequestMapping("/users")  
public class UserController {
    
      
   @Autowired  
   private UserRepository userRepository;
   @GetMapping  
   public List<User> findAll() {
    
      
       return userRepository.findAll();  
   }
   @GetMapping("/{id}")  
   public User findById(@PathVariable Long id) {
    
      
       return userRepository.findById(id);  
   }
   @PostMapping  
   public void save(@RequestBody User user) {
    
      
       userRepository.save(user);  
   }
   @DeleteMapping("/{id}")  
   public void deleteById(@PathVariable Long id) {
    
      
       userRepository.deleteById(id);  
   }  
}

The above code shows a simple JPA-based user management system. In this system, we use JPA for data persistence and query, and use the Spring Boot framework to process Web requests.

8. JPA learning materials

The official website of JPA (Java Persistence API) is: https://java.net/projects/jpa/
On this website, you can find the latest specification documents, API reference and some sample codes of JPA. Here are some helpful links:

  • JPA 2.2 specification document: https://java.net/projects/jpa/downloads/jpa-2.2-spec.pdf
  • JPA 2.1 specification document: https://java.net/projects/jpa/downloads/jpa-2.1-spec.pdf
  • JPA Tutorial: https://java.net/projects/jpa/tutorial/
    In addition, there are many learning materials and tutorials about JPA. Here are some suggestions:
  1. "Java Persistence API: The Book": An introductory book on JPA written by Roger Counsell, one of the main authors of the JPA specification. This book details the basic concepts, APIs, and best practices of JPA.

  2. "Mastering Java Persistence: JPA, Hibernate, and Spring Data JPA": This book, written by renowned Java EE author Martin Fowler, covers advanced topics in JPA, including Hibernate and Spring Data JPA.

  3. "JPA in Action": This book, written by Donald Kuchling, provides a wealth of examples and scenarios from actual projects, and is suitable for readers with a certain foundation in JPA.

  4. "Java Persistence with Hibernate": This book, written by Gavin King (one of the main authors of Hibernate) and James Fowler, mainly introduces Hibernate, but also covers the basics of JPA.Insert image description here

  5. Online courses: There are many free or paid online courses about JPA on the Internet. For example, you can find some high-quality courses on Coursera, Udemy, MOOC and other platforms.
    When learning JPA, you can practice it in combination with actual projects, so that you can better understand the principles and applications of JPA. At the same time, refer to more information and community discussions to help solve problems encountered and improve your skills.

Guess you like

Origin blog.csdn.net/superdangbo/article/details/132892881