'When does the hibernate session gets closed

I have created the following entities.

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @OneToMany(mappedBy = "student")
    private List<Book> books;
}
@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @ManyToOne
    @JoinColumn(name = "STUDENT_ID")
    private Student student;
}

My controller looks like this

@RestController
public class Controller {

    MyService myService;

    public Controller(MyService myService) {
        this.myService = myService;
    }

    @GetMapping("student")
    public List<Book> getBooksForStudent(Long id) {
        return myService.getBooks(id);
    }
}

The service is as follows.

public class MyService {

    @Autowired
    private StudentRepo studentRepo;

    public List<Book> getStudent(Long id) {
        Optional<Student> studentOptional = studentRepo.findById(id);
        return studentOptional.map(Student::getBooks).orElseThrow(IllegalArgumentException::new);
    }
}

I am getting the list of books as expected. But as I'm having lazy loaded list for books I should be getting a LazyInitializationException. I have not added transnational to the method and I'm returning the list of books from the entity itself without mapping it to a DTO. Why is the hibernate session not getting closed after the end of the method?



Solution 1:[1]

@RestController is transactional by default. Spring boot automatically registers an OpenEntityManagerInViewInterceptor when you use a web application/you use JPA. Refer @RestController methods seem to be Transactional by default, Why?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abhinav Prasun