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:
@Entity
public class Company {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@OneToMany(mappedBy="company",orphanRemoval=true,cascade=CascadeType.ALL)
private List<Store> stores = new ArrayList<>();
// getters and setters...
}
@Entity
public class Store {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(nullable=false)
private String name;
@ManyToOne
@JoinColumn(nullable = false, name = "company_id")
private Company company;
// getters and setters
}
Service layer:
@Service
@Transactional
public class CompanyService {
@Autowired
private CompanyRepository companyRepository;
public Company getCompany() {
Company company = companyRepository.findOne(1000L);
return company;
}
}
Controller layer:
@RestController
@RequestMapping("/company")
public class CompanyResource {
@Autowired
private CompanyService companyService;
@GetMapping
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);
}
}
application.yml
spring:
datasource:
driverClassName: org.postgresql.Driver
url: url_to_database
username: something
password: something
jpa:
database: POSTGRESQL
hibernate:
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.