如何使用休眠条件连接 3 个表?

时间:2021-05-08 03:12:23

标签: java hibernate predicate hibernate-criteria

我有三张桌子。

  1. 父母
  2. parent_child_mapping
  3. 孩子

我想加入 3 个表并使用“CriteriaBuilder”和“Predicate”按子名称过滤。 我如何使用“CriteriaBuilder”和“Predicate”来实现以下 sql 查询。

  SELECT p.parent_id
  FROM parent p
  JOIN parent_child_mapping pcmap on p.parent_id = pcmap.mapping_parent_id
  JOIN child c on pcmap.mapping_child_id = c.child_id
  WHERE c.child_name = 'abc'

父实体

@Entity
@Table(name = "parent")
public class Parent {

    private static final long serialVersionUID = 1L;
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "parent_id")
    private Long parentId;
    
    ....

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "mappingParentId")
    private Collection<ParentChildMapping> parentChildMappingCollection;
}

父子映射实体

@Entity
@Table(name = "parent_child_mapping")
public class ParentChildMapping{

    private static final long serialVersionUID = 1L;
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "mapping_id")
    private Long mappingId;
       
    @JoinColumn(name = "mapping_child_id")
    @ManyToOne(optional = false)
    private ChildEntity mappingChildId;
    
    @JoinColumn(name = "mapping_parent_id")
    @ManyToOne(optional = false)
    private ParentEntity mappingParentId;
}

子实体

@Data
@Entity
@Table(name = "child")
public class Child implements Serializable 
{
    private static final long serialVersionUID = 1L;
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "child_id")
    private Long childId;
    
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "child_name")
    private String childName;
}

1 个答案:

答案 0 :(得分:1)

您只需为每个实体创建一个根并将条件添加到 where 子句中。像这样:

Root<Parent> parent = criteriaQuery.from(Parent.class);
Root<ParentChildMapping> mapping = criteriaQuery.from(ParentChildMapping.class);
Root<Child> child = criteriaQuery.from(Child.class);
criteriaQuery.select(parent.get("parentId"));
criteriaQuery.where(
  criteriaBuilder.and(
    criteriaBuilder.equal(parent.get("parentId"), mapping.get("mappingParentId")),
    criteriaBuilder.equal(child.get("childId"), mapping.get("mappingChildId")),
    criteriaBuilder.equal(child.get("childName"), "abc")
  )
);