I have the following setup
@Entity
@Table(name = "Product")
public class Product implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@OneToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
private final List<Item> itemlist = new ArrayList<Item>();
//some other attributes, getter/setter
}
@Entity
@Table(name = "Item")
public class Item implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private Date startDate;
//some other attributes, getter/setter
}
The connection beween these classes is only unidirectional. If bidirectional connection is better (e.g. in terms of performance)?
How can i query all Items which were launched after a date (startDate) and to a specific product are assigned?
I try to implementing this with criteria api:
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Item> criteriaQuery = criteriaBuilder.createQuery(Item.class);
criteriaQuery = criteriaQuery.distinct(true);
Metamodel m = em.getMetamodel();
EntityType<Product> Product_ = m.entity(Product.class);
Root<Product> root = criteriaQuery.from(Product_);
Join join = root.join("itemlist");
Predicate condition = criteriaBuilder.equal(join.get("product"), selectedProduct);
criteriaQuery.where(condition);
criteriaQuery.select(join);
TypedQuery<Item> tq = em.createQuery(criteriaQuery);
System.out.println("result " + tq.getResultList());
I got the exception:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.test.Product.itemlist, no session or session was closed
Is there a problem with my Query or with the lazy itemlist?