春季交易注释 [英] Spring Transactional Annotation
问题描述
我正在尝试更好地使用Spring的 @Transactional
属性.我了解它基本上是在事务中包装标记为 @Transactional
的方法的内容.像我在这里所做的那样,将服务/业务层方法标记为事务性而不是实际的DAO方法是否合适?
I'm trying to get a better handle on the use of Spring's @Transactional
attribute. I understand that it basically wraps the contents of the method marked as @Transactional
in a transaction. Would it be appropriate to mark a service/business layer method as transactional, as opposed to the actual DAO method, as I have done here?
服务实施
public class UserServiceImpl implements UserServiceInt{
@Autowired
private UserServiceDAO serviceDAO;
@Override
public User getUser(int id){
return serviceDAO.getUser(id);
}
@Override
@Transactional
public void updateUserFirstName(int id, String firstName) throws SomeException{
User userToUpdate = getUser(id);
if(userToUpdate == null){
throw new SomeException("User does not exist");
}
userToUpdate.setFirstName(firstName);
serviceDAO.updateUser(userToUpdate);
}
}
DAO实施
public class UserServiceDAOImpl implements UserServiceDAOInt{
@PersistenceContext(unitName="myUnit")
private EntityManager entityManager;
@Override
public void updateUser(User user){
entityManager.merge(user);
}
}
我什至不确定是否需要合并电话.由于UserServiceImpl类中没有EntityManager声明,Spring如何知道要使用哪个EntityManager?
I'm not even sure if the call to merge is even necessary. How does Spring know which EntityManager to use since there isn't an EntityManager declare in the UserServiceImpl class?
推荐答案
当Service类中的方法具有多个数据库调用并且我们希望所有调用时,我们用 @Transactional
标记Service层应该发生或没有人应该发生,或者我们可以说如果任何呼叫失败,则整个交易应该 rollback
.如果我们不属于这一标准,那么我们也可以在DAO层上选择 @Transactional
.
We mark a Service layer with @Transactional
when a method in a Service class is having multiple database calls and we want either all calls should happen or no one should happen or we can say if any call fail then whole transaction should rollback
. If we are not falling under this criteria then we can opt for @Transactional
on DAO layer also.
由于UserServiceImpl类中未声明EntityManager,Spring如何知道要使用哪个EntityManager?
Spring从 persistence.xml
(来自classpath)引用 EntityManager
,其结构类似于以下内容:
Spring is referring the EntityManager
from persistence.xml
(from classpath), whose structure is similar to below:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="myUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/YourDatasource</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
这篇关于春季交易注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!