我有以下设置
@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
}
这些类之间的连接只是单向的。如果双向连接更好(例如在性能方面)?
如何查询在某个日期 (startDate) 之后启动并分配给特定产品的所有项目?
我尝试使用标准 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());
我得到了例外:
org.hibernate.LazyInitializationException:未能延迟初始化角色集合:com.test.Product.itemlist,没有会话或会话已关闭
我的查询或惰性项目列表有问题吗?