I can't seem to get my Spring JPA config working correctly. I have a Spring REST service. If I set all the entities to FetchType.EAGER, everything works as expected. But I don't want to do that for the obvious reasons.
When I set my entities to FetchType.LAZY, I get the following error:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.service.entities.MyEntity.lawfirmCaseDecisions, could not initialize proxy - no Session
I've looked through other similar SO questions but my still running into the same issue. Here's my config:
@Configuration
@Import(EnvironmentProvider.class)
@EnableTransactionManagement
@Slf4j
public class DataSourceProvider {
@Autowired EnvironmentProvider envProvider;
@Bean
DataSource dataSource() {
final EnvConfig env = envProvider.envConfig();
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUrl(env.findProperty("db.url"));
dataSource.setPortNumber( Integer.parseInt(env.findProperty("db.port")) );
dataSource.setUser(env.findProperty("db.username"));
dataSource.setPassword(env.findProperty("db.password"));
return dataSource;
}
@Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPackagesToScan("com.offtherecord.service.core.entities");
//entityManagerFactoryBean.setPersistenceUnitName("OTR");
HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
entityManagerFactoryBean.setJpaVendorAdapter(va);
Properties ps = new Properties();
ps.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
// ps.put("hibernate.show_sql", "true"); //useful for debugging
ps.put("hibernate.format_sql", "true");
entityManagerFactoryBean.setJpaProperties(ps);
return entityManagerFactoryBean;
}
@Bean
@PersistenceContext
JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().nativeEntityManagerFactory);
return transactionManager;
}
}
For quick testing, I added the @Transactional annotation on my controller method. In the below code, the UserEntity class has a list of Orders which doesn't get populated:
@RequestMapping(method = RequestMethod.GET)
@Transactional
public ResponseEntity<GetOrdersResponse> getOrders() {
UserEntity activeUser = controllerUtil.getActiveUser();
...
return new ResponseEntity<>(new GetOrdersResponse(), HttpStatus.OK);
}
I'd love to get past this!
userEntity.getOrders(). Can you add this method call if not already there and see that works? - Nitin Arora