SpringBoot Fast JPA Integration Completes CRUD

Posted by jhonrputra on Wed, 22 Sep 2021 19:18:25 +0200

Foreword: When talking about Java Web, many little partners know SSH. This H stands for Hibernate framework, but what is JPA? I believe many beginners have heard about it but are not very clear. First, the full name of JPA is Java Persistence.API, JPA is a standard specification based on O/R mapping. In this specification, JPA only defines standard rules and does not provide implementation, but users need to use them in the way defined in the specification. Currently, the main implementations of JPA are Hibernate, EclipseLink, OpenJPA, etc. In fact, because Hibernate dominates the field of data access resolution technology, the standard of JPA is basically Hibe.In addition, the Spring Framework provides us with Spring Data JPA to reduce the amount of code we use when using JPA.

1. Introduction to Spring Data Jpa

1.1,JPA

JPA(Java Persistence API), or Java Persistence API, is the Java Persistence Specification (JSR 338, packaged in javax.persistence) that Sun officially proposed after JDK5.0.

The emergence of JPA is mainly to simplify the development of persistence layer and integrate ORM technology, ending the situation of separate ORM frameworks such as Hibernate, TopLink, JDO. JPA is developed on the basis of existing ORM frameworks, which are easy to use and highly scalable.

(1) Overall, JPA includes the following three technologies:

ORM Mapping Metadata: Supports both XML and annotation forms of metadata that describe mapping relationships between objects and tables

API: Operate entity objects to perform CRUD operations

Query Language: Avoid tight coupling of the program's SQL statements by querying data through object-oriented rather than database-oriented query language (JPQL)

(2) ORM framework

ORM is named Object-Relational Mapping: Object-Relational Mapping. Simply to operate a database without using the original JDBC methods, the ORM framework has come out (mybatis, hibernate, etc.)However, there are too many ORM frameworks, a wide variety of them, you have a set of standards and I have a set of standards, if you want to change the framework to achieve the project, you may have to rewrite from the beginning.

Sun introduced the new JPA ORM specification for two reasons:

First, simplify the development of existing Java EE and Java SE applications;

Second, Sun wants to integrate ORM technology to normalize the world.

1.2,Spring Data Jpa

Spring Data JPA is part of the Spring Data family and easily implements a JPA-based repository. This module handles enhanced support for the JPA-based data access layer, which makes it easier to build Spring-driven applications that use data access technologies.

Overall, JPA is the ORM specification, Hibernate, TopLink, and so on are specific implementations of the JPA specification. This benefit is that developers can develop persistence layers for the JPA specification, while the underlying implementations can be switched. Spring Data Jpa adds another layer of abstraction (the Repository layer implementation) on top of JPA, greatly simplifying the cost of persistence layer development and ORM framework switching.

2. SpringBoot Integrated JPA

2.1. Prepare MySQL data, create a new table t_user

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `t_id` int(11) NOT NULL,
  `t_name` varchar(255) DEFAULT NULL,
  `t_age` int(11) DEFAULT NULL,
  `t_address` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`t_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--------

2.2, Introducing JPA and MySQL Driver Dependencies

      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--JPA-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!--Database Driver-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

2.3, application.yml configuration data source, and JPA

In the future, we will modify the application.properties file to configure the application.yml configuration. The.Yml configuration file and the.Properties configuration should be clearer and more hierarchical, and the configuration information can be clearly understood.

server:
  port: 8088

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/shankeng?serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
      naming:
        physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
    show-sql: true

2.4, UserEntity entity class

Create an entity class UserEntity based on field correspondence in the database

package com.hs.demo.entity;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name="t_user")
public class UserEntity implements Serializable {
    @Id
    @GeneratedValue
    @Column(name="t_id")
    private Long id;
    @Column(name="t_name")
    private String name;
    @Column(name="t_age")
    private int age;
    @Column(name="t_address")
    private String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Long getId() {

        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

2.5, UserJPA creation

Now that we have created the entity class, we need to use SpringDataJPA to complete the database operation. We create a new UserJPA interface and inherit the interface within SpringDataJPA as the parent class:

package com.hs.demo.jpa;

import com.hs.demo.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import javax.transaction.Transactional;
import java.io.Serializable;
import java.util.List;

/**
 * JPA There are many interfaces available that don't have to write their own underlying encapsulation anymore
 *
 * By defining a method according to naming rules, you can operate on databases such as queries: findBy + entity attribute name, get + entity class name + By + entity attribute name,...
 * You can also use the @Query annotation to query directly...
 *
 */
public interface UserJPA extends JpaRepository<UserEntity, Long>, JpaSpecificationExecutor<UserEntity>, Serializable {


    //Find all users by name
    List<UserEntity> findByName(String userName);

    //Find a single user by name
    UserEntity getUserEntityByName(String userName);

    //Find individual users by name using Query annotations
    @Query("select u from UserEntity u where u.name = ?1")
    UserEntity findUserEntityByName(String userName);

//    //Find individual users by name using Native Query
//    @Query(value = "SELECT * FROM T_USER WHERE NAME = hs", nativeQuery = true)
//    UserEntity findUserEntityByName(String userName);

    //Delete users by name
    @Transactional
    void deleteByName(String userName);

}

Our UserJPA inherits the JpaRepository interface (simple data manipulation interface provided by SpringDataJPA), JpaSpecificationExecutor (complex query interface provided by SpringDataJPA), and Serializable (serialization interface).
We don't need to do anything else, because SpringBoot and SpringDataJPA will do it all for us. SpringDataJPA uses class proxy to make subinterfaces that inherit its interfaces exist as Spring-managed beans, which means we can use the @Autowired annotation directly in Spring-managed beans.

Matters needing attention

1. When asynchronous queries, use the @ResponseBody annotation to write the return value to the Http response body, otherwise the front end will not get the return value.

2. When deleting, the delete method uses @Transactional Return to inject the method into the transaction.

2.6. Create a new UserController class and write CRUD methods

package com.hs.demo.controller;

import com.hs.demo.entity.UserEntity;
import com.hs.demo.jpa.UserJPA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserJPA userJPA;

    /**
     * Query all data
     *
     * @return
     */
    @RequestMapping("/list")
    public List<UserEntity> list() {
        return  userJPA.findAll();
    }

    @RequestMapping("/save")
    public UserEntity save(UserEntity entity) {
        return    userJPA.save(entity);
    }

    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public List<UserEntity> delete(Long id) {
        userJPA.deleteById(id);
        return userJPA.findAll();
    }

   @RequestMapping("/find")
    //Receive Front End Request Parameters, Normal-Request Parameter Name is the same as the Parameters of the Controller Method
    public UserEntity find(String name) {
        return userJPA.getUserEntityByName(name);
    }

}

2.7, Start SpringBoot Project Start Test

After starting the project, direct access 127.0.0.1:8088/user/list appears empty because there is no data in the database. First insert data into the database, enter 127.0.0.1:8088/user/save in the browser? Name=admin&age=16&address=Shanghai

The effect is as follows:

 

After repeated insertions, access 127.0.0.1:8088/user/list again as shown in the following figure:

2.8. JPA Summary

This blog shows how to use Spring Boot JPA to interact with MySQL data. You can see that using JPA can greatly reduce Dao code and greatly improve development efficiency.JPA is very convenient for single-table queries, and also provides the name of the method naming rule definition method and the @Query annotation query; of course, this is just a simple single-table query. Next, I will describe how JPA joins multiple-table queries, dynamic conditional queries, paging, and so on.

Reference link:

JPA@Query Usage

Method Naming Rule provided by Spring Data JPA defines the name of the method

Summary of Several Ways for SpringMVC Controller to Receive Front End Parameters

Topics: jpa