I am able to save an entity without @Transactional
in my Spring Boot application. I only noticed this because I wasn't able to update an entity until I added @Transactional
to the save
method within EmployeeService.java
.
I don't have @Transactional
annotated at the class level. The only other place it is found is on methods in my Service layer that do not pertain to the save
method. My EmployeeDAO
does not extend JPARepository
. It is annotated with @Repository
. I have spring-boot-starter-data-jpa
as a dependency. I am not manually beginning or committing a transaction either.
EmployeeRestController.java
@PostMapping("/employees")
public void addEmployee(@RequestBody Employee employee) {
employee.setId(0);
employeeService.save(employee);
}
EmployeeService.java
public void save(Employee employee) {
emplDAO.save(employee);
}
EmployeeDAO.java
@Override
public void save(Employee employee) {
Session currentSession = em.unwrap(Session.class);
currentSession.saveOrUpdate(employee);
}
By default in Spring Boot Web applications spring.jpa.open-in-view
is set to true
.
Most probably it is the reason
From Spring Boot Reference Guide:
If you are running a web application, Spring Boot by default registers
OpenEntityManagerInViewInterceptor
to apply the “Open EntityManager in View” pattern, to allow for lazy loading in web views. If you do not want this behavior, you should setspring.jpa.open-in-view
tofalse
in yourapplication.properties
.
See also: