0

我有以下设置

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

我的查询或惰性项目列表有问题吗?

4

1 回答 1

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();

呼!!!!

费德里科

于 2013-08-08T07:58:22.723 回答