Spring Boot development of web applications-using simpler JPA

The content of this section transforms the web project to support a simpler JPA method.

JPA stands for Java Persistence API. JPA describes the object-relational table du mapping relationship through JDK 5.0 annotations or XML, and persists the entity objects at runtime to the database.

1. Introduce dependencies

To use JPA, you need to introduce related dependencies. JPA is a subproject of Spring Data. The specific dependencies are as follows

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

2. Entity class transformation

package com.kinglead.demo.entity;
 ​
 import lombok.AllArgsConstructor;
 import lombok.Data;
 import lombok.NoArgsConstructor;
 ​
 import javax.persistence.*;
 import java.io.Serializable;
 ​
 @Data //添加getter、setter方法
 @NoArgsConstructor   //无参构造函数
 @AllArgsConstructor  //所以参数构造函数
 @Entity  //声明为JPA实体
 @Table(name = "t_user") //该标注与@Entity标注并列使用,用于指明数据库的表名
 public class User implements Serializable {
     private static final long serialVersionUID = -21070736985722463L;
 ​
     @Id //指明主键
     @GeneratedValue(strategy= GenerationType.AUTO)
     private Long id;
 ​
     @Column(name = "name", columnDefinition = "姓名")  //指明字段
     private String name;
 ​
     @Column(name = "password", columnDefinition = "密码") //指明字段
     private String password;
 ​
 }

@Entity annotation declares the User class as a JPA entity

@Table annotation indicates the name of the database table

@Id annotation indicates the primary key of the table

The @GeneratedValue annotation indicates the primary key generation strategy, strategy= GenerationType.AUTO depends on the database field to generate ID

@Column annotation indicates the field of the table

Note: There are still many notes about JPA entities, so I won't explain them here. I will write an article to explain them later. Interested students can also go to the official website to continue learning: https://spring.io/projects/spring-data-jpa

3. Declare the JPA repository

package com.kinglead.demo.dao;
 ​
 import com.kinglead.demo.entity.User;
 import org.springframework.data.jpa.repository.JpaRepository;
 ​
 public interface UserRepository extends JpaRepository<User, Long>{
 }

UserRepository interface needs to inherit JpaRepository interface, JpaRepository defines many CRUD operation methods. Inheriting JpaRepository needs to pass in 2 parameters, the first is the persistent entity class, and the second is the type of the primary key id. If the JpaRepository interface class is implemented, then UserRepository does not need to write the implementation class at all, because Spring Data JPA will automatically generate it for us when the project starts. (In addition, you can also implement the CrudRepository interface to declare the JPA repository. The biggest difference between it and JpaRepository is that JpaRepository supports paging query)

4. Add a custom method in the repository

In addition to CRUD provided by JpaRepository, we can also customize methods, such as findAllByNameAndPassword method

package com.kinglead.demo.dao;
 ​
 import com.kinglead.demo.entity.User;
 import org.springframework.data.jpa.repository.JpaRepository;
 ​
 public interface UserRepository extends JpaRepository<User, Long> {
 ​
     User findByNameAndPassword(String name, String password);
 ​
 }

 

Here, the custom findAllByNameAndPassword method does not need to be written and implemented separately. As long as the custom method name follows the specification (Domain-Specific Language DSL), JPA can automatically generate it.

In addition, if the specification does not support actual requirements, you can use @Query annotations on custom methods to write native SQL. For example, the findAllByNameAndPassword method can also be declared like this. Of course, for this simple query, it is not recommended to do so, just let JPA handle it automatically.

 @Query(value = "select id,name,password from t_suer where name=? and password=?", 
        nativeQuery = true)
 User findByNameAndPassword(String name, String password);

 5. UserServiceImpl user service implementation transformation

package com.kinglead.demo.service.impl;
 ​
 import com.kinglead.demo.dao.UserRepository;
 import com.kinglead.demo.entity.User;
 import com.kinglead.demo.service.UserService;
 import org.springframework.stereotype.Service;
 ​
 import javax.annotation.Resource;
 import java.util.List;
 ​
 @Service
 public class UserServiceImpl implements UserService {
 ​
     @Resource
     private UserRepository userRepository;
 ​
     /**
      * 新增用户
      */
     @Override
     public User insert(User user) {
         return userRepository.save(user);
     }
 ​
     /**
      * 通过用户名和密码查询用户
      */
     @Override
     public User queryByNameAndPassword(User user) {
         return userRepository.findByNameAndPassword(user.getName(), user.getPassword());
     }
 ​
     /**
      * 查询用户列表
      */
     @Override
     public List<User> queryAll() {
         return userRepository.findAll();
     }
 ​
 }

 

6. Other

The other codes involved in the project remain unchanged, just keep the same as the third section.

Under the test http://localhost:8080/user/userList , the user list can also be returned

 

 

Guess you like

Origin blog.csdn.net/a159357445566/article/details/108626562
Recommended