JPA2 - 使用 Criteria API 作为动态查询递归地获取连接实体的子实体

JPA2 - Getting child entities of joined entities recursively using Criteria API as Dynamic Query

我想了解如何使用 Criteria API 而不是 JPQL 来应用某些条件,特别是如果可以使用 Criteria 以与 JPQL 相同的方式通过 Join 层次结构递归地从 Joins 获取子实体。

更新

Tiny 和 Chris 的评论促使我首先弄清楚我要实现的目标:

我的示例有 4 个实体,如下图所示。 Enitem 与 Ensources 具有 ManyToOne 关系。 Entopics 与 Enitems 具有 OneToMany 关系。 Entopics 与 SegmentsNew 具有 OneToMany 关系。

我正在构建一个搜索页面,用户可以通过在搜索条件中输入尽可能多或尽可能少的内容来找到所选项目。在下面的示例中,搜索 "Corporate Law" 应该 return 公司法部分中的所有项目(即使没有输入任何其他内容)。

我的实体:

物品:

@Entity
@Table(name = "enitem")

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "itemid")
private Integer itemid;
@Size(max = 500)
@Column(name = "itemname")
private String itemname;
@Column(name = "daterec")
@Temporal(TemporalType.DATE)
private Date daterec;
@Lob
@Size(max = 65535)
@Column(name = "itemdetails")
private String itemdetails;
private String enteredby;
@OneToMany(mappedBy = "items")
private Collection<Endatamaster> endatamasterCollection;
@JoinColumn(name = "topicid", referencedColumnName = "topicid")
@ManyToOne
private Entopic topics;
@JoinColumn(name = "sourceid", referencedColumnName = "sourceid")
@ManyToOne
private Ensource source;

熵:

public class Entopic implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "topicid")
private Integer topicid;
@Size(max = 500)
@Column(name = "topicname")
private String topicname;
@Size(max = 500)
@Column(name = "description")
private String description;
@Column(name = "locksec")
private boolean locksec;
@JoinColumn(name = "segmentid", referencedColumnName = "SEGMENTID")
@ManyToOne
private Segmentnew segments;
@JoinColumn(name = "marketid", referencedColumnName = "marketid")
@ManyToOne
private Enmarkets markets;
@OneToMany(mappedBy = "topics")
private Collection<Enitem> enitemCollection;

资源:

@Entity
@Table(name = "ensource")
@NamedQueries({
@NamedQuery(name = "Ensource.findAll", query = "SELECT e FROM Ensource e")})
public class Ensource implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "sourceid")
private Integer sourceid;
@Size(max = 500)
@Column(name = "sourcename")
private String sourcename;
@Size(max = 500)
@Column(name = "description")
private String description;

@JoinColumn(name = "typeid", referencedColumnName = "typeid")
@ManyToOne
private Enitemtype entype;

新细分:

public class Segmentnew implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "SEGMENTID")
private Integer segmentid;
@Size(max = 255)
@Column(name = "SEGMENTNAME")
private String segmentname;
@OneToMany(mappedBy = "segments")
private Collection<Entopic> entopicCollection;
@JoinColumn(name = "sectorId", referencedColumnName = "SECTORID")
@ManyToOne
private Sectorsnew sectors;

所需的 JPQL 字符串表示形式为:

Select e FROM Enitems e WHERE e.topics.topicid = :topicid 
AND e.source.sourceid = :sourceid; AND e.topics.segments.segmentid = :segmentid  

搜索页面使用 JSf Primefaces:

<p:panelGrid columns="2">

                    <p:outputLabel value="Sectors: "/>
                    <p:selectOneMenu value="#{sectorBean.sectorid}"
                                     filter="true">
                        <f:selectItem itemValue="0" itemLabel="NULL"/>
                        <f:selectItems value="#{sectorBean.secList}"
                                       var="sect"
                                       itemLabel="#{sect.sectorname}"
                                       itemValue="#{sect.sectorid}"/>
                        <f:ajax listener="#{segmentsBean.segFromSec}" render="segs"/>
                    </p:selectOneMenu>

                    <p:outputLabel value="Segments: "/>
                    <p:panel id="segs">

                        <p:selectOneMenu value="#{queryBean.segmentid}"
                                         rendered="#{not empty segmentsBean.menuNormList}">

                            <f:selectItems value="#{segmentsBean.menuNormList}"
                                           var="segs"
                                           itemLabel="#{segs.segmentname}"
                                           itemValue="#{segs.segmentid}"/>
                        </p:selectOneMenu>

                    </p:panel>

                    <p:outputLabel value="Topics: "/>
                    <p:selectOneMenu value="#{queryBean.topicid}" filter="true">
                        <f:selectItem itemValue="" itemLabel="NULL"/>
                        <f:selectItems value="#{clienTopicBean.publicTopMenu}"
                                       var="pubs"
                                       itemLabel="#{pubs.topicname}"
                                       itemValue="#{pubs.topicid}"/>


                    </p:selectOneMenu>

                    <p:outputLabel value="Type: "/>
                    <p:selectOneMenu value="#{typeBean.typeid}" filter="true">
                        <f:selectItem itemValue="" itemLabel="NULL"/>
                        <f:selectItems value="#{typeBean.menuList}"
                                       var="type"
                                       itemLabel="#{type.typename}"
                                       itemValue="#{type.typeid}"/>

                        <f:ajax listener="#{sourceBean.sourceFromType}" render="src"/>
                    </p:selectOneMenu>

                    <p:outputLabel value="Sources: "/>
                    <p:panel id="src">

                        <p:selectOneMenu value="#{queryBean.sourceid}"
                                         rendered="#{not empty sourceBean.sourceListNorm}">

                            <f:selectItems value="#{sourceBean.sourceListNorm}"
                                           var="srcs"
                                           itemLabel="#{srcs.sourcename}"
                                           itemValue="#{srcs.sourceid}"/>
                        </p:selectOneMenu>

                    </p:panel>
                </p:panelGrid>

这就是我正在尝试使用 CAPI:

public List<Enitem> superQ(Integer topicid, Integer sourceid,
        Integer segmentid) {
    em.clear();

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(Enitem.class);
    Root<Enitem> rt = cq.from(Enitem.class);

    cq.select(rt);
    cq.distinct(true);

    List<Predicate> criteria = new ArrayList<Predicate>();
    Predicate whereClause = cb.conjunction();
    // if () {
    Path<Entopic> topJoin = rt.get("topics");


    if (topicid != 0) {

        ParameterExpression<Integer> p
                = cb.parameter(Integer.class, "topicid");
        whereClause = cb.and(whereClause, cb.equal(topJoin.get("topicid"), p));
    }
    if (segmentid != 0) {

        ParameterExpression<Integer> p
                = cb.parameter(Integer.class, "segmentid");
        whereClause = cb.and(whereClause, cb.equal(topJoin.get("segments").get("segmentid"), p));
    }
    //}

    if (sourceid != 0) {
        ParameterExpression<Integer> p
                = cb.parameter(Integer.class, "sourceid");
        whereClause = cb.and(whereClause, cb.equal(rt.get("source").get("sourceid"), p));
    }

//    if(whereClause.getExpressions().isEmpty()) {
//        throw new RuntimeException("no criteria");
//    }
    cq.where(whereClause);

    TypedQuery q = em.createQuery(cq);
    if (topicid != 0) {
        q.setParameter("topicid", topicid);
    }
    if (segmentid != 0) {
        q.setParameter("segmentid", segmentid);
    }

    if (sourceid != 0) {
        q.setParameter("sourceid", sourceid);
    }

    return q.getResultList();

}

声明 if(entityName != 0) 而不是 if(entityName != null) 很重要,我之前就是这样做的,这导致应用程序要求所有参数由用户。这可能是因为 null 的整数值实际上是数字零?

生成的SQL:

SELECT DISTINCT t1.itemid, t1.daterec, t1.ENTEREDBY, t1.itemdetails, t1.itemname, 
t1.sourceid, t1.topicid FROM enitem t1 LEFT OUTER JOIN entopic t0 ON (t0.topicid 
= t1.topicid) LEFT OUTER JOIN ensource t2 ON (t2.sourceid = t1.sourceid) WHERE 
(((t0.topicid = ?) AND (t2.sourceid = ?)) AND (t0.segmentid = ?))

该应用程序的行为是动态的,因为用户只需在搜索页面中输入任何单个值,然后 return 会生成一个与该值相对应的列表。 我现在遇到的问题是,即使我已经在方法开始时清除了 EntityManager,如果我进行第二次查询,也会得到相同的结果 return。所以应用程序只有在重新启动后才能工作。我需要引用实体吗?

使用 From 和 join 都可以为您提供可以转换为根接口的对象,从而允许链接连接。
尝试类似的东西:

public List<Enitem> superQ(Integer topicid, Integer sourceid,
      Integer segmentid) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(Enitem.class);
    Root<Enitem> rt = cq.from(Enitem.class);

    cq.select(rt);
    cq.distinct(true);

    List<Predicate> criteria = new ArrayList<Predicate>();
    Predicate whereClause = cb.conjunction();
    if ((topicid != null)||(segmentid != null)){
      Path<Entopic> topJoin =rt.get("topics");
      if(topicid != null) {
          ParameterExpression<Integer> p =
                  cb.parameter(Integer.class, "topicid");
          whereClause = cb.and(whereClause, cb.equal(topJoin.get("topicid"), p));
      }
      if(segmentid != null) {
        ParameterExpression<Integer> p =
                cb.parameter(Integer.class, "segmentid");
        whereClause = cb.and(whereClause, cb.equal(topJoin.get("segments").get("segmentid"), p));
      }
    }

    if(sourceid != null) {
      ParameterExpression<Integer> p =
               cb.parameter(Integer.class, "sourceid");
      whereClause = cb.and(whereClause, cb.equal(rt.get("source").get("sourceid"), p));
    }


    if(whereClause.getExpressions().isEmpty()) {
        throw new RuntimeException("no criteria");
    }
    cq.where(whereClause);
}

除非指定了需要连接的参数,否则这将产生一些没有任何连接的东西,并且将像提供的 JPQL 一样使用内部连接。

事实证明 JPA 的逻辑是正确的,但问题出在 Web 框架中,这意味着我必须相应地调整我的 JPA。 JSF 不接受 'null' 作为搜索页面中整数的定义,只接受数值或仅接受“”。从 :

更改 if 语句
if(entity != null);

if(entity != 0);

导致应用程序按预期运行。这解决了这个问题中的问题。感谢 Chris 和 Tiny 的帮助