I am facing Transaction errors such:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: app.Parent.children, could not initialize proxy - no Session
Here on parent.getChildren().size()
.
But I do have an @Transactional
on @Service
methods:
- 1 transaction on
createFactory()
to create a factory and give the entitymanager - 1 transaction on
create()
to create the entity
@Path("api/parents")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Controller
public class ParentResource {
@Autowired
private ParentService parentService;
@POST
public Parent create(Parent parent) {
ParentFactory parentFactory = parentService.createFactory(parent);
return parentService.create(parent);
}
}
@Service
public class ParentService {
@PersistenceContext
private EntityManager em;
@Transactional
public ParentFactory createFactory(Parent parent) {
return new ParentFactory(parent, em);
}
@Transactional
public Parent create(ParentFactory parentFactory) {
return parentFactory.create();
}
}
// No Transactional annotation
public class ParentFactory {
private Parent parent;
private EntityManager em;
public ParentFactory(Parent parent, EntityManager em) {
this.parent = parent;
this.em = em;
}
public parent create() {
if(parent.getChildren().size() < 3) { // Exception here
em.persist(this.parent);
}
}
}
I'd like to be able to test when my Hibernate Session is alive or not, so that I can check when it's lost and why.
Thanks !