Spring Transactional Annotation

I am trying to get the best descriptor for using the Spring @Transactional attribute. I understand that it basically wraps the contents of a method marked as @Transactional in a transaction. It would be appropriate to mark the service / business layer method as transactional rather than the actual DAO method, as I did here?

Service implementation

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); } } 

Implement DAO

 public class UserServiceDAOImpl implements UserServiceDAOInt{ @PersistenceContext(unitName="myUnit") private EntityManager entityManager; @Override public void updateUser(User user){ entityManager.merge(user); } } 

I'm not even sure if you need a call to merge. How does Spring know which EntityManager to use, since EntityManager is not declared in the UserServiceImpl class?

+6
source share
1 answer

We mark the service level with @Transactional when the method of the Service class has several database queries, and we want either all calls to occur, or no one should happen, or we can say that if any call failed, then the whole transaction should rollback . If we do not @Transactional this criterion, we can also select @Transactional on the DAO layer.

How does Spring know which EntityManager to use, since EntityManager is not declared in the UserServiceImpl class?

Spring refers to the EntityManager from persistence.xml (from the class path), whose structure is similar to the structure:

 <?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> 
+2
source

Source: https://habr.com/ru/post/988578/


All Articles