Executing an update/delete query报错

If JPA prompts Executing an update/delete query, it must be because the Service layer does not add @Transactional and then @Modifying in the method.

Abnormal scene

When spring-boot+jpa performs new, modified and deleted operations:

public interface UserRepository extends JpaRepository<User , Integer>{

    @Modifying
    @Query(value="update User set state = ?1,lastupdatetime = ?2 where id= ?3")
    void updateUser(int state,Date nowDate,Integer id);

}

异常: Executing an update/delete query

solution

Because of jpa requirements,'without transaction support, update and delete operations cannot be performed'.

So on the other hand, @Transactional must be added to the Service layer or the Repository layer to indicate that this is a transaction-level operation. Additions, deletions, changes, and checks are all transaction-level operations, and it is ok to treat it as a specification.

 

Why are annotations added to the service layer?


Combining the characteristics of the transaction, it is easy to explain why it is added to the service layer. If our transaction annotation @Transactional is added to the dao layer, then as long as we make additions, deletions and changes to the database, we must submit a transaction. The characteristics of such a transaction will not be able to play out, especially the consistency of the transaction. When there is a concurrency problem, the user The data found from the database will be biased.
In general, our service layer can call multiple dao layers, we only need to add a transaction annotation @Transactional to the service layer, so that we can process multiple requests in one transaction, and the characteristics of the transaction will be fully utilized.

 

What is a transaction?


In the database, the so-called transaction refers to a group of logical operation units, that is, a group of sql statements. When a part of the operation in this unit fails, the entire transaction is rolled back, and the commit is completed only when everything is correct. The key to judging whether the transaction is successfully configured is whether the transaction will roll back when an exception occurs

Four characteristics of transaction


1. Atomicity (Atomicity) Atomicity
means that a transaction is an indivisible unit of work, and the operations in the transaction either all happen or never happen .

2. Consistency (Consistency)
transaction must make the database from a consistent state to another consistent state. (Data is not destroyed

3. Isolation (Isolation)
transaction isolation means that the execution of a transaction cannot be interfered by other transactions.

4. Durability (Durability) Durability
means that once a transaction is committed, its changes to the data in the database are permanent. Even if the system is restarted, it will not be lost.

Guess you like

Origin blog.csdn.net/My_SweetXue/article/details/114031221