Issue
I'm new to Hibernate and I'm getting the following error when trying to pull a collection from a =n entity model,
Error occured converting lead: failed to lazily initialize a collection of role: [...] could not initialize proxy - no Session
I've tried adding the @Transactional but I haven't had any success.
Relevant code:
Policy.java
@Entity
@Table(name = "policy")
public class Policy {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "policy")
private Set<Item> items = new HashSet<>();
...
}
IntercomApiImpl
@Component
public class IntercomApiImpl implements IntercomApi {
private final String apiToken;
private final PolicyFeeDao policyFeeDao;
private final SimpleDateFormat dobFormat;
@Autowired
public IntercomApiImpl(@Qualifier("intercomApiToken") String apiToken,
PolicyFeeDao policyFeeDao) {
this.apiToken = apiToken;
Intercom.setToken(this.apiToken);
this.policyFeeDao = policyFeeDao;
this.dobFormat = new SimpleDateFormat("yyyy-MM-dd");
}
private Map<String, CustomAttribute> getPolicyAttrs(Policy policyToPay) {
Map<String, CustomAttribute> customAttrs = Maps.newHashMap();
Set<Item> items = policyToPay.getItems();
customAttrs.put("item_count",
CustomAttribute.newIntegerAttribute("item_count", items.size()));
return customAttrs;
}
}
I also have this set up (I'm not sure it's relevant):
@Bean
public LocalSessionFactoryBean sessionFactoryBean() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan("com.app.model");
sessionFactoryBean.setHibernateProperties(hibernateProperties());
return sessionFactoryBean;
}
protected Properties hibernateProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", getProperty("hibernate.dialect"));
return properties;
}
@Bean
public HibernateTransactionManager transactionManager() {
return new HibernateTransactionManager(sessionFactoryBean().getObject());
}
I've tried adding @Transactional to getPolicyAttrs() but that didn't work. Any idea what I am missing?
Solution
@Transactional
won't work in this case because you are not fetching your Policy in this method, you are passing it in as a parameter instead.
You can change your OneToMany
relationship to be EAGER so the child objects are always fetched with parent, thou this might lead to performance issues. If you want to keep it lazy, you will have to explicitly call on the lazy collection to initialize it, by using Hibernate.initialize()
:
Hibernate.initialize(policyToPay.getItems());
Answered By - veljkost