SpringBoot 2.0 Basic Case (09): Integrating JPA persistence layer framework to simplify database operations

Keywords: Java Hibernate Spring JDBC

Introduction of JAP Framework

JPA(Java Persistence API), which means Java persistence API, is the Java persistence specification proposed by Sun after JDK 5.0. The main purpose is to simplify the development of persistence layer and integrate ORM technology, to end the situation of Hibernate, TopLink, JDO and other ORM frameworks operating independently. JPA is developed on the basis of existing ORM framework. It is easy to use and has strong scalability.

Integration with SpringBoot 2.0

1. Core Dependence

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

2. Configuration file

spring:
  application:
    name: node09-boot-jpa
  datasource:
    url: jdbc:mysql://localhost:3306/data_jpa?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

Several configuration instructions of ddl-auto
1)create
Each time hibernate is loaded, the last generated table is deleted, and then a new table is generated according to the bean class, which can easily lead to data loss. (It is recommended to use it when creating for the first time.)
2)create-drop
Each time hibernate is loaded, tables are generated according to the bean class, but the tables are automatically deleted as soon as session Factory is closed.
3)update
When hibernate is loaded for the first time, the structure of the table is built automatically according to the bean class. When hibernate is loaded later, the table structure is updated automatically according to the bean class. Even if the table structure changes, the rows in the table still exist without deleting the previous rows.
4)validate
Every time hibernate is loaded, validation creates the database table structure, which only compares with the tables in the database, does not create new tables, but inserts new values.

3. Entity class objects

This is the table structure generated from this object.

@Table(name = "t_user")
@Entity
public class User {
    @Id
    @GeneratedValue
    private Integer id;
    @Column
    private String name;
    @Column
    private Integer age;
    // Eliminate GET SET
}

4. Use of JPA Framework

Define the interface of object operation and inherit the core interface of JpaRepository.

import com.boot.jpa.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User,Integer> {

    // But conditional query
    User findByAge(Integer age);
    // Multi-Conditional Query
    User findByNameAndAge(String name, Integer age);
    // Custom Query
    @Query("from User u where u.name=:name")
    User findSql(@Param("name") String name);
}

5. Encapsulating a Service Layer Logic

import com.boot.jpa.entity.User;
import com.boot.jpa.repository.UserRepository;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class UserService {
    @Resource
    private UserRepository userRepository ;
    // Preservation
    public void addUser (User user){
        userRepository.save(user) ;
    }
    // Query by age
    public User findByAge (Integer age){
        return userRepository.findByAge(age) ;
    }
    // Multi-Conditional Query
    public User findByNameAndAge (String name, Integer age){
        return userRepository.findByNameAndAge(name,age) ;
    }
    // Custom SQL Query
    public User findSql (String name){
        return userRepository.findSql(name) ;
    }
    // Modify according to ID
    public void update (User user){
        userRepository.save(user) ;
    }
    //Delete a data based on id
    public void deleteStudentById(Integer id){
        userRepository.deleteById(id);
    }
}

3. Test Code Block

import com.boot.jpa.JpaApplication;
import com.boot.jpa.entity.User;
import com.boot.jpa.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = JpaApplication.class)
public class UserJpaTest {
    @Resource
    private UserService userService ;
    @Test
    public void addUser (){
        User user = new User() ;
        user.setName("Know a smile");
        user.setAge(22);
        userService.addUser(user);
        User user1 = new User() ;
        user1.setName("cicada");
        user1.setAge(23);
        userService.addUser(user1);
    }
    @Test
    public void findByAge (){
        Integer age = 22 ;
        // User{id=3, name ='Know a smile', age=22}
        System.out.println(userService.findByAge(age));
    }
    @Test
    public void findByNameAndAge (){
        System.out.println(userService.findByNameAndAge("cicada",23));
    }
    @Test
    public void findSql (){
        // User{id=4, name='cicada', age=23}
        System.out.println(userService.findSql("cicada"));
    }
    @Test
    public void update (){
        User user = new User() ;
        // If the primary key does not exist, it will be added to the library by adding the primary key itself.
        user.setId(3);
        user.setName("Ha-ha-ha");
        user.setAge(25);
        userService.update(user) ;
    }
    @Test
    public void deleteStudentById (){
        userService.deleteStudentById(5) ;
    }
}

4. Source code address

GitHub Address: Know a smile
https://github.com/cicadasmile
 Code Yun Address: Know a smile
https://gitee.com/cicadasmile

Posted by mortona on Thu, 15 Aug 2019 07:40:25 -0700