将 Sql 查询转换为条件查询

时间:2021-02-16 17:11:33

标签: hibernate-criteria criteria-api

我将这些实体映射成这样:

 @Entity
 @Table(name="work_stage")
 public class WorkStage {
   @Id
   private BigDecimal id;

   @ManyToMany(fetch = FetchType.EAGER)
   @JoinTable(name = "work_stage_x_locality", joinColumns = @JoinColumn(name = "id_work_stage"),
              inverseJoinColumns = @JoinColumn(name = "id_locality"))
   private List<Locality> localityList;
}

 @Entity
 @Table(name="locality")
 public class Locality {
   @Id
   private BigDecimal id;  
   @Column(name="name")
   private String name;

   @ManyToMany(mappedBy = "localityList")
   private List<WorkStage> workStageList;
}

我想使用 Criteria API 执行以下查询:

select * from work_stage
where id in (
select ws.id from work_stage ws inner join work_stage_x_locality wsl on ws.id = wsl.id_work_stage 
where wsl.id_locality in (74, 75, 76));

我尝试在子查询中编写该连接,但没有提前。

后期编辑: 我能够像这样编写内部选择:

Expression<String> exp = root.join(sqlQuery.getKey()).get("id");
predicates.add(exp.in((List<BigDecimal>) sqlQuery.getValue()))

1 个答案:

答案 0 :(得分:0)

所以我是如何设法编写它的:

CriteriaQuery<WorkStage> query = builder.createQuery(WorkStage.class);
               Subquery<BigDecimal> subqueryWorkStageId = query.subquery(BigDecimal.class);
               Root<WorkStage> subqueryWorkStageRoot = subqueryWorkStageId.from(WorkStage.class);
               subqueryWorkStageId.select(subqueryWorkStageRoot.get("id"))
                       .where(subqueryWorkStageRoot.join("localityList")
                               .in((List<BigDecimal>) sqlQuery.getValue()));

               predicates.add(query.select(root)
                       .where(root.get("id").in(subqueryWorkStageId)).getRestriction());