【问题标题】:How to join 3 table using hibernate criteria?如何使用休眠条件加入 3 个表?
【发布时间】:2021-07-30 06:44:16
【问题描述】:

我有三张桌子。

  1. 父母
  2. parent_child_mapping
  3. 孩子

我想加入 3 个表并使用“CriteriaBuilder”和“谓词”按子名称过滤。 如何使用“CriteriaBuilder”和“谓词”实现以下 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;
}

【问题讨论】:

  • ParentChildMapping 的意义何在?你不能简单地使用@ManyToMany吗?

标签: java hibernate predicate hibernate-criteria


【解决方案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")
  )
);

【讨论】:

    猜你喜欢
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    相关资源
    最近更新 更多