我需要帮助理解我在Hibernate中观察到的以下行为。
,我现在可以通过添加'hack'来使代码正常工作,所以我想删除它。实体类:
Department.java
- Long departmentId; (Id of department)
- String departmentName; (Name of department)
@OneToOne(fetch = FetchType.LAZY)
- Account account; (department account)
Account.java
@ElementCollection(fetch=FetchType.LAZY)
@CollectionTable(name="ACCOUNTS_BATCHES")
- Set<Long> batches;
@ElementCollection(fetch=FetchType.LAZY)
@CollectionTable(name="ACCOUNTS_SECTIONS")
- Set<Long> sections;
Since the fetchType is defined as Lazy, I had to do HibernateUtils.initializeAndUnproxy(), so my code is like this:
Line 1: Account account = HibernateUtils.initializeAndUnproxy((department.getAccount());
Line 2: map.put("batches", HibernateUtils.initializeAndUnproxy(account.getBatches()));
Line 3: account.getBatches().size();
Line 4: map.put("sections", HibernateUtils.initializeAndUnproxy(account.getSections()));
Line 5: account.getSections().size();
I only need to pass the ids of batches and sections on UI.
This works fine, but to make it work I had to explicitly add Line 3 and Line 5 (where we are doing .size())
If I remove Line 3 and Line 5, then it throws LazyInitializationException.
My question is that why it doesn't work without adding these 2 lines and when we add it, what is happening in these 2 lines which is making it work.
Set is of type java.util.Set