Question: No LazyInitializationException in controller


No LazyInitializationException in controller

Answers 0
Added at 2016-12-22 10:12

On my project I'm using Spring Boot with Hibernate 5 and Postgresql 9.4. Now I'm facing a problem. I've got a @OneToMany relationship with LAZY fetching. When I try to get this collection outside of a transaction, no exception is thrown. For me that's not a good behavior - I'm expecting LazyInitializationException which is not thrown. Spring Boot project is new and clean. Everything set to default so far.

Here's my code:

Domain classes:

public class Company {
    private Long id;
    private List<Store> stores = new ArrayList<>();

    // getters and setters...

public class Store {
    private Long id;
    private String name;
    @JoinColumn(nullable = false, name = "company_id")
    private Company company;

    // getters and setters

Service layer:

public class CompanyService {
    private CompanyRepository companyRepository;

    public Company getCompany() {
        Company company = companyRepository.findOne(1000L);
        return company;

Controller layer:

public class CompanyResource {
    private CompanyService companyService;

    public ResponseEntity<?> getCompany() {
        Company company = companyService.getCompany();
        // HERE I WOULD EXPECT LazyInitializationException
        String storeName = company.getStores().get(0).getName();
        // But storeName is normally filled and resource responds 200
        return new ResponseEntity<>(HttpStatus.OK);


        driverClassName: org.postgresql.Driver
        url: url_to_database
        username: something
        password: something
        database: POSTGRESQL
            ddl-auto: create-drop

Hibernate enable_lazy_load_no_trans property set as default to false. I also tried to enable show-sql and when I debug I can see that hibernate executes SQL selects during company.getStores().get(0).getName() execution. Does anyone know how to pretend this? I want to get a lazy loading exceptions outside of transactions.

Source Show
◀ Wstecz