With commented @Transactional I get LazyInitializationException, when I uncommnet @Transactional test works fine.
Why @Transactional is not needed to execute query and to access Order object, but is needed to access order items ?
the outer loop
for (Order order : result) works fine,
exception is in inner
for (Item item:order.getItems())Why ?
Code:
@Test
// @Transactional
public void testSimpleCriteria() {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Order> criteria = builder.createQuery(Order.class);
Root<Order> orderRoot = criteria.from(Order.class);
criteria.select(orderRoot);
criteria.where(builder.like(orderRoot.<String>get("customer"), "J%"));
TypedQuery<Order> typedQuery = entityManager.createQuery(criteria);
List<Order> result= typedQuery.getResultList();
for (Order order : result) { // here is no exception, order is fetched correctly !
for (Item item:order.getItems()) { // exception appears only here !!
System.out.println("item: " + item);
}
}
}
top of stack trace is
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.javatech.app.Order.items, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
I suppose, that if it where in web app, than the same exception would appear in the same place, and if I would use OpenSessionInViewFilter the code would work fine.
So does OpenSessionInViewFilter do the same as @Transactional ?