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>
Arpit source share