Criteria API加入一个惰性Collection

时间:2013-02-17 23:30:05

标签: hibernate collections lazy-loading criteria-api

我有以下设置

@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,没有关闭会话或会话

我的查询或懒项目列表是否有问题?

1 个答案:

答案 0 :(得分:0)

这可能是陈旧的,但我手边有代码。这就是我解决这个问题的方法:

    CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> queryRoot = criteriaQuery.from(Product.class);

    Predicate idPredicate = criteriaBuilder.equal(queryRoot.get(Product_.id), id);
    criteriaQuery.where(idPredicate);

    TypedQuery<Product> typedQuery = em.createQuery(criteriaQuery);

    Product theProduct = typedQuery.getSingleResult();

    //this triggers the lazy relationship
    theProduct.getItemsList();

HTH !!!!

费德里科