【问题标题】:JPA criteria builder wrapper with join带有连接的 JPA 标准构建器包装器
【发布时间】:2018-11-08 04:39:13
【问题描述】:

如何使用 JPA Criteria builder 构建 DTO,并在由一对多关系链接的表上加入连接?

在文档中,没有同时使用包装器和连接案例的示例。

JPA Doc

例如:

EntityA {
   String name;

   @OneToMany
   Set<EntityB> items;

   ...
}


Wrapper {
   name;
   Set<EntityB> items;
}

【问题讨论】:

  • 如果我没记错的话,你不能。投影不处理连接。也许您可能想查询EntityB 的列表,而不是EntityAitems。将items 列表传递给一个 Dto 对象,该对象获取该列表并从其中一个中提取父级名称。

标签: java jpa criteria criteria-api


【解决方案1】:

如果我没记错的话,你不能。投影不处理连接。也许您可能想要查询EntityB 的列表而不是EntityAitems 的列表,并将项目列表传递给一个Dto 对象,该对象采用父实体及其列表。可以肯定的是,这不是您想要的,但应该完成工作。所以,举个例子:

@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;
    }

并使用它:

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

【讨论】:

    猜你喜欢
    • 2011-04-21
    • 2020-02-21
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 2015-02-23
    • 1970-01-01
    相关资源
    最近更新 更多