问题描述
我正在学习如何使用JPA和Hibernate和MySQL数据库创建REST API,并且看到了@Transactional注释.有人可以解释此注释的用途吗?
I'm learning about how to create REST API with JPA and Hibernate and a MySQL database and I see this @Transactional annotation. Can someone explain what is the use of this annotation?
例如,我有一个简单的DAO类:
For example I have this simple DAO class:
@Repository
public class EmployeeDAOHibernateImpl implements EmployeeDAO {
// define field for entitymanager
private EntityManager entityManager;
// set up constructor injection
@Autowired
public EmployeeDAOHibernateImpl(EntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
@Transactional
public List<Employee> findAll() {
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
// create a query
Query<Employee> theQuery =
currentSession.createQuery("from Employee", Employee.class);
// execute query and get result list
List<Employee> employees = theQuery.getResultList();
// return the results
return employees;
}
}
您可以看到用于findAll()方法的@Transactional,但是如果删除此@Transactional,则会得到相同的输出...那么,此@Transactional的用途是什么?
You can see the @Transactional used for findAll() method, but if I delete this @Transactional I get the same output... then what is the use of this @Transactional?
推荐答案
@Transactional
批注用于在事务中执行某些方法/类(=内部的所有方法)的情况.
@Transactional
annotation is used when you want the certain method/class(=all methods inside) to be executed in a transaction.
假设用户A
希望将100 $转移给用户B
.会发生什么:
Let's assume user A
wants to transfer 100$ to user B
. What happens is:
- 我们将A的帐户减少了100 $
- 我们将100美元添加到B的帐户中
让我们假设在执行1)
之后和执行2)
之前引发了异常.现在我们会有某种不一致的地方,因为A
损失了100美元,而B
一无所获.交易意味着全部或全部.如果方法中某处引发异常,则更改不会持久保存在数据库中.发生rollback
之类的事情.
Let's assume the exception is thrown after succeeding 1)
and before executing 2)
. Now we would have some kind of inconsistency because A
lost 100$ while B
got nothing.Transactions means all or nothing. If there is an exception thrown somewhere in the method, changes are not persisted in the database. Something called rollback
happens.
如果未指定@Transactional
,则每个数据库调用将处于不同的事务中.
If you don't specify @Transactional
, each DB call will be in a different transaction.
这篇关于JPA和Hibernate对@Transactional的使用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!