Reputation: 12436
I am trying to create a bean which manipulates database via JPA. The methods are all correctly annotated with @Transactional(readOnly = false) - until now this was handled by calls from Servlet and everything worked well.
Now I want to do some database manipulation in its init method:
@Component
public class MyBean {
@PostConstruct
@Transactional(readOnly = false)
public void init() {
MyEntity myEntity = ...;
...
em.persist(myEntity);
}
(The case is simplified). Like this I am getting exceptions "No session or session was closed". Obviously the transactions are correctly started only when run by requests in Servlets, but not from the actual bean. How can I achieve this even by running from the bean itself?
Thanks.
Upvotes: 1
Views: 448
Reputation: 692073
AFAIK, Spring doesn't use the transactional proxies around your beans to call the PostConstruct methods (which BTW, are not part of the external interface of the bean most of the time).
Try calling the init()
method of MyBean
from another bean (where MyBean is injected), or even from a ServletContextListener
.
Upvotes: 4