简体   繁体   English

带连接的 JPA 标准构建器包装器

[英]JPA criteria builder wrapper with join

How can I build a DTO using JPA Criteria builder with a join on tables linked by a one-to-many relation?如何使用 JPA Criteria builder 构建 DTO,并连接由一对多关系链接的表?

In the documentation, there is no example using both a wrapper and join cases.在文档中,没有同时使用包装器和连接案例的示例。

JPA Doc JPA文档

For instance :例如 :

EntityA {
   String name;

   @OneToMany
   Set<EntityB> items;

   ...
}


Wrapper {
   name;
   Set<EntityB> items;
}

If I remember right, you can't.如果我没记错的话,你不能。 Projection doesn't handle joins.投影不处理连接。 Perhaps you might want to query a list of EntityB instead of an EntityA with items and pass the items list to a Dto object that takes the parent entity and its list.也许您可能想要查询EntityB的列表而不是带有itemsEntityA并将项目列表传递给采用父实体及其列表的 Dto 对象。 Not what you want, to be sure, but should get the job done.不是你想要的,当然,但应该完成工作。 So, by example:所以,举个例子:

@Entity
public class EntityA {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @OneToMany(mappedBy="a")
    private Set<EntityB> bs;

@Entity
public class EntityB {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    private EntityA a;

public class WrapperDto {
    private EntityA a;
    private List<EntityB> bs;
    public WrapperDto(EntityA a, List<EntityB> bs) {
        this.a = a;
        this.bs = bs;
    }

and to use it:并使用它:

    tx.begin();
    EntityA a = new EntityA();
    EntityB b1 = new EntityB(); 
    EntityB b2 = new EntityB();
    b1.setA(a);
    b2.setA(a);
    em.persist(a);
    em.persist(b1);
    em.persist(b2);
    tx.commit();
    em.clear();

//  projection with join fetch doesn't work.  
//  em.createQuery("select new dto.WrapperDto( a, bs ) from EntityA a left outer join fetch a.bs bs where a.id = 1", WrapperDto.class).getResultList();

//  a possible solution
    EntityA aFound = em.find(EntityA.class, 1L);
    List<EntityB> bs = em.createQuery("select b from EntityB b where b.a = :a", EntityB.class).setParameter("a", aFound).getResultList();
    WrapperDto dto = new WrapperDto(aFound, bs);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM