A: Just two steps! Eclipse+Maven builds the first Spring Boot project.

The Spring Boot database is connected to the MySQL database.

In this paper, on the basis of the previous, using Spring Data Jpa for MySQL database CRUD — add (Create), query (Retrieve), Update (Update) and Delete (Delete) operations.

Spring Data Jpa

What is JPA? Let’s see what Baidu says. JPA, short for Java Persistence API, is a JDK 5.0 annotation or XML mapping describing object-relational tables and persisting run-time entity objects to a database.

The general idea of JPA is basically the same as existing ORM frameworks such as Hibernate, TopLink and JDO. In general, JPA includes the following three technologies:

  • ORM mapping metadata

JPA supports two forms of metadata, XML and JDK5.0 annotations. Metadata describes the mapping between objects and tables, and the framework persists entity objects to database tables.

  • API

It’s used to manipulate entity objects, perform CRUD operations, and the framework does everything for us in the background, freeing developers from tedious JDBC and SQL code.

  • Query language (SQL)

This is an important aspect of persistence operations, where data is queried in an object-oriented rather than database-oriented query language, avoiding tight coupling of the program’s SQL statements.

Spirng Data Jpa is a set of framework provided by Spring to simplify Jpa development. By writing Dao layer interface according to the agreed “method naming rule”, access and operation to database can be realized without writing interface implementation.

In the process of learning, query a lot of information, I think blog garden this summary is quite good: Spring Boot (five) : Spring data JPA use

Let’s start CRUD:

Increase (Create)

Add a method to userController.java:

    @RequestMapping("/addUser")
    @ResponseBody
    public User addUser(String userName, String PassWord) {
        User user = new User();
        user.setUserName(userName);
        user.setPassWord(PassWord);
        userRepository.save(user);
        return user;
    }
Copy the code

Use the Postman to http://localhost:8080//user/addUser? The userName = Laplace&PassWord = math:

Mysql > select * from database where id = 5, username = Laplace, password = math;

To facilitate the query, use the same operation to insert some data.

Query (Retrieve)

The previous article covered simple findAll and findByUserName. Here are some custom queries.

Most of Spring Data’s SQL can be implemented according to the method name defined by the way, and you can also write your own SQL statement to query.

Use @Query annotations on SQL Query methods, including @modifying where necessary when deleting and Modifying SQL Query methods. You can also add @Transactional support for things as needed.

SELECT * FROM USER t WHERE T. id >= 6; SELECT * FROM USER t WHERE T. id >= 6;

java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List

Add to Dao:

    @Query("SELECT * FROM USER t WHERE t.id >= 6")
    List<User> getUser(a);
Copy the code

This is because Jpa cannot automatically map query results to custom entities. Write the path of the entity class, and then add the name of the entity class instead of the name of the table.

    @Query("SELECT new com.example.demo.domain.User(t.id,t.userName,t.passWord) FROM User t WHERE t.id >= 6")
    List<User> getUser(a);
Copy the code

We also need to add the corresponding constructor in the middle of the entity class user.java (as in the SQL statement above) to return the object of the entity class:

    public User(Long id, String userName, String passWord) {
        super(a);this.id = id;
        this.userName = userName;
        this.passWord = passWord;
    }
Copy the code

The contents of userController.java are as follows:

    @RequestMapping("/getUser")
    public List<User> getUser(a) {
        List<User> res = userRepository.getUser();
        return res;
    }
Copy the code

Use the Postman to http://localhost:8080//user/getUser:

Here’s what’s in the database:

Update (Update)

Updates can be made using the save method; The updates are made using custom SQL statements, and try the @pipelineannotation.

The Dao:

    @Modifying
    @Query("UPDATE User u SET u.userName = ? 1 WHERE u.id = ? 2. "")
    void updateUserNameById(String userName, Long id);
Copy the code

Controller:

    @RequestMapping("/updateUserNameById")
    @Transactional
    public String updateUserNameById(@RequestParam("name")  String name, @RequestParam("id") Long id) {
        userRepository.updateUserNameById(name, id);
        return "Update successful";
    }
Copy the code

Use the Postman to http://localhost:8080//user/updateUserNameById? Name = AAAAAA&id = 6:

You can see that the database has changed:

Delete (Delete)

Delete records based on ID and add directly to Controller:

    @RequestMapping("/deleteUserById")
    public String deleteUserById(@RequestParam("id") Long id) {
        userRepository.deleteById(id);
        return "Deleted successfully";
    }
Copy the code

Use the Postman to http://localhost:8080//user/deleteUserById? Id = 11:

The delete operation can be completed:

conclusion

In this paper, Spring Boot JPA was used for data operation. It is not difficult to find that using JPA can greatly reduce Dao layer code and improve development efficiency.