How to gracefully implement the addition, deletion, modification and query of Mysql? After reading it, you will

Posted by robin105 on Mon, 24 Jan 2022 14:35:41 +0100

Then, in the previous period, the data was queried without writing an sql in the previous period. What if you want to save or update the data? Can you write your own sql?

Save data

@GetMapping("save")//Save data

public void save(@RequestBody User user){
    userJpa.save(user);
}

Add the above method in UserController. Using @RequestBody to receive data, and then calling userJpa's save method to save data, next we use postman to try.

After execution, go to the database to see the data. The data has been added.

ps: the primary key of our database table is generated by self increment, so there is no need to specify the primary key manually when calling the save method. In addition, I can see the console output:

Hibernate: insert into user (age, dpt_id, email, head_img, name) values (?, ?, ?, ?, ?)

You can see that sql is actually executed in the background.

Delete data:

@GetMapping("delete")//Delete data by primary key

public void delete(@RequestParam("id")Long id){
    userJpa.deleteById(id);
}

postman execution:

localhost:8080/user/delete?id=6

Guys, go to the database again. The newly added data has been deleted. Look at the console again.

Hibernate: select user0_.id as id1_0_0_, user0_.age as age2_0_0_, user0_.dpt_id as dpt_id3_0_0_, user0_.email as email4_0_0_, user0_.head_img as head_img5_0_0_, user0_.name as name6_0_0_ from user user0_ where user0_.id=?
Hibernate: delete from user where id=?

Why are there two sql statements? In fact, jpa queries the data to determine whether it exists, and then performs the deletion action. What happens if the data doesn't exist? You can execute the deletion request again. Is there an error in the background? If it needs to be deleted in the actual business, it is not to be judged. It is very troublesome. Don't worry. We can write our own sql deletion. What should we do? Then look down.

Delete by name

New method of UserController

@GetMapping("deleteByUserName")//Delete data by user name
public void deleteByUserName(@RequestParam("name")String name){
    this.userJpa.deleteByName(name);
}

UserJpa new method:

@Modifying//Tell jpa that this is the update or delete method, which will change the data in the database

@Query(value = "delete from user where name=:name",nativeQuery = true)//jpa will replace: name with the name in the parameter @ Param

public int deleteByName(@Param("name") String name);//Parameter variable

postman execute request

localhost:8080/user/deleteByUserName?name=Jone

Update data:

New method of UserController

@GetMapping("update")//Update data

public void update(@RequestParam("id")Long id,@RequestParam("name")String name){
    User user = this.userJpa.findById(id).get();//First, load the data with the id
    user.setName(name);//Change data
    this.userJpa.save(user);//Save data
}

postman execute request

localhost:8080/user/update?id=2&name=Jack123

Secretly look at the database. Has the data changed?

Custom query

New method in UserController

@GetMapping("findByAge")//Find data by age

public List<User> findByAge(@RequestParam("age")Integer age){
    return this.userJpa.findByAge(age);
}

New method in UserJpa:

@Query(value = "select * from user where age>?1",nativeQuery = true)

public List<User> findByAge(Integer Age);

Postman execute request:

localhost:8080/user/findByAge?age=20

Is the query result in line with expectations? jpa is so powerful.

Let's summarize the common usage of jpa:

  1. First, you need to define an interface that inherits from JpaRepository, and use the @ Repository annotation on the interface class to tell springboot that this is a Repository class

  2. Use @ Resource to inject this interface into external calls

  3. You can use many custom methods in the jpa interface class. For example, the bold font is the method defined in UserJpa.

  4. If the methods are not enough for our business, you can write your own methods in UserJpa. The powerful jpa syntax hardly requires you to write sql statements. Of course, you can define your own methods if your business needs.

  5. If you want to write your own sql, you can define your own methods on UserJpa, but you don't need to implement them yourself. Annotate the method with @ Query. Write sql or hql with value in @ Query. If you write sql, you need to use nativeQuery=true

  6. Write your own jpa method and use @ Query annotation, but if the sql statement of update or delete is executed in it, use @ Modifying annotation.
    Well, it's simple. jpa is so powerful. More jpa syntax and content are waiting for you to explore. In the next issue, we will talk about Transaction.

More original reading: https://javawu.com

Topics: MySQL Spring Boot