jpa-with-hibernate icon indicating copy to clipboard operation
jpa-with-hibernate copied to clipboard

Removing Transactional Still Working

Open tharari21 opened this issue 1 year ago • 0 comments

Hello,

This is not an issue with any of the lectures I simply misunderstood something and need some help. The way I understand @Transactional is that it keeps the session (Hibernate) or persistence context (JPA) open and every database change in the method is under one transaction. Also if transactional is not placed on a method, a new persistence context will be created and destroyed for each line of code that accesses entity manager. I wanted to test that this understanding was correct so I took the retrievePassportAndAssociatedStudent test method and removed @Transactional. You stated in the course that because fetch type is lazy, the persistence context closes after we call em.find() and therefore the following call to passport.getStudents() should cause a "could not initialize proxy" exception. Well after removing @Transactional my code still tested fine with no exceptions and I really cannot understand why. I ensured fetch type is lazy both sides of relationship.

@Test
//    @Transactional
    public void retrievePassportAndAssociatedStudent() {
        Passport passport = em.find(Passport.class, 40001L);
        logger.info("Passport -> {}", passport);
        logger.info("Passport Student-> {}", passport.getStudent());
    }

tharari21 avatar Apr 17 '23 19:04 tharari21