Hi,
I get a LazyInitializationException because the session (that is still open at that time) is closed when entering a enum-value-specific method.
Step 1)
I retrieve an item from the database in a method annotated with the @Transactional annotation.
Step 2)
I use an enum to retrieve some values from the item.
Code:
MyEnum.getValues(item)
Code:
public enum MyEnum{
SOME_ENUM_VALUE {
public List<String> doGetValues(Item item) {
List<String> values = new ArrayList<String>();
for(String obj : item.getWire().getEmbargoAuthors()) { //LazyInitializationException is thrown
//do something
}
return values;
}
};
public final List<String> getValues(Item item) {
//item.getWire().getEmbargoAuthors().size(); //If this line is uncommented everything is fine. The session is still open.
return doGetValues(item);
}
protected abstract List<String> doGetValues(Item item);
The really weird thing is that the test I created to reproduce the problem works fine:
Code:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/test-ApplicationContext.xml"})
public class ItemDaoImplTest {
@Resource(name = "itemDao")
private ItemDao itemDao;
@Test
@Transactional
public void testTransactionInStaticMethod() {
final Item item = itemDao.get(1L);
MyEnum.SOME_ENUM_VALUE.getValues(item); //Does not throw a LazyInitializationException
}
}
The entities:
Code:
@Entity
@Table(name = "ITEMS")
public final class Item {
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "wire_id", nullable = false)
@ForeignKey(name = "item_wire_fk")
private Wire wire;
...
}
Code:
@Entity
@Table(name = "WIRES")
public final class Wire {
@Id
private Long id;
@OneToMany(mappedBy = "wire")
private List<EmbargoAuthor> embargoAuthors = new ArrayList<EmbargoAuthor>();
...
}
Any idea how this can be solved without using eager loading?
The version of hibernate I am using:
Code:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.9.Final</version>
</dependency>