2013-02-17 64 views
0

我有以下设置标准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 
} 

beween这些类的连接仅仅是单向的。如果双向连接更好(例如性能方面)?

如何查询在日期(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,没有会话或会话被关闭

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

回答

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 !!!!

Federico

+0

这样做在任何生产代码和你的表现将会下降。你最终会有多个查询。所以,你的解决方案的作品这是一个可怕的解决方案。使用Criteria API或Entity Graph,您可以更好地编写自己的JPQL。 – harogaston 2017-07-07 20:18:35