SpringBoot integrates JPA persistence layer framework to simplify database operation

  • 2021-09-24 22:10:43
  • OfStack

Directory integration with SpringBoot 2.0
1. Core Dependencies 2. Configuration Files 3. Entity Class Objects
4. Usage of the JPA Framework
5. Encapsulate the source code address of a service layer logic test code block

Integration with SpringBoot 2.0

1. Core dependencies


<!-- JPA Framework  -->
<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

Description of Several Configurations of ddl-auto
1) create
Every time hibernate is loaded, the last generated table is deleted, and then a new table is generated again according to bean class, which is easy to cause data loss. (It is recommended to use it when creating it for the first time).
2) create-drop
Each time hibernate is loaded, a table is generated based on the bean class, but when sessionFactory1 is turned off, the table is automatically deleted.
3) update
The first load hibernate according to the bean class will automatically establish the structure of the table, after loading hibernate according to the bean class automatically update the table structure, even if the table structure changes but the table rows still exist will not delete the previous row.
4) validate
Each time hibernate is loaded, validation creates a database table structure that compares with the tables in the database, does not create a new table, but inserts new values.

3. Entity class objects

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;
    //  Omission  GET SET
}

4. Usage of JPA Framework

The interface that defines the operation of the object inherits the JpaRepository core interface.


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 queries 
    User findByAge(Integer age);
    //  Multi-condition query 
    User findByNameAndAge(String name, Integer age);
    //  Custom Query 
    @Query("from User u where u.name=:name")
    User findSql(@Param("name") String name);
}

5. Encapsulate 1 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 ;
    //  Save 
    public void addUser (User user){
        userRepository.save(user) ;
    }
    //  Query by age 
    public User findByAge (Integer age){
        return userRepository.findByAge(age) ;
    }
    //  Multi-condition query 
    public User findByNameAndAge (String name, Integer age){
        return userRepository.findByNameAndAge(name,age) ;
    }
    //  Customize SQL Query 
    public User findSql (String name){
        return userRepository.findSql(name) ;
    }
    //  According to ID Modify 
    public void update (User user){
        userRepository.save(user) ;
    }
    // According to id Delete 1 Bar data 
    public void deleteStudentById(Integer id){
        userRepository.deleteById(id);
    }
}

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(" Cicadas 1 Laugh ");
        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=' Cicadas 1 Laugh ', 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 this primary key does not exist, it will be added to the warehouse by adding the primary key 
        user.setId(3);
        user.setName(" Ha ha 1 Laugh ");
        user.setAge(25);
        userService.update(user) ;
    }
    @Test
    public void deleteStudentById (){
        userService.deleteStudentById(5) ;
    }
}

Source code address

GitHub Address: Cicada 1 Smile
https://github.com/cicadasmile/spring-boot-base
Code Cloud Address: Cicada 1 Smile
https://gitee.com/cicadasmile/spring-boot-base

The above is the SpringBoot integration JPA persistence layer framework, simplified database operation details, more about SpringBoot integration JPA persistence layer framework information please pay attention to other related articles on this site!


Related articles: