JPA,CriteriaBuilder和List

时间:2018-03-14 15:53:02

标签: jpa java-ee

假设我有以下实体:

    @Entity
    @Table(name = "COMPETENCY")
    public class Competency {

        @Id
        @Getter
        @Setter
        @Column(name = "ID")
        private Integer id;

        @Getter
        @Setter
        @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
        @JoinColumn(name = "COMP_ID", referencedColumnName = "ID")
        private Set<ProficiencyLevel> proficiencyLevels = new HashSet<ProficiencyLevel>();
    }

    @Entity
    @Table(name = "PROFICIENCY_LEVEL")
    public class ProficiencyLevel {

        @Id
        @Getter
        @Setter
        @Column(name = "ID")
        private Integer id;

        @Getter
        @Setter
        @Column(name = "LEVEL_NAME", nullable = false)
        private String levelName;
    }

请注意,Competency和ProficiencyLevel之间存在1:N的关系。

是否可以通过使用CriteriaBuilder执行以下操作:

select competency.proficiencyLevels pl where pl.name like '%something%'

提前致谢。

1 个答案:

答案 0 :(得分:0)

如果要选择名称与给定字符串匹配的ProficiencyLevel,属于给定的Competency对象,您可以这样做:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<ProficiencyLevel> cq = cb.createQuery(ProficiencyLevel.class);
Root<Competency> root = cq.from(Competency.class);
Join<Competency, ProficiencyLevel> join = root.join("proficiencyLevels");
cq.select(join);
cq.where(cb.equal(root, someCompetency));
cq.where(cb.like(join.get("name"), "%something%"));
TypedQuery<ProficiencyLevel> q = em.createQuery(cq);
List<ProficiencyLevel> results = q.getResultList();

如果ProficiencyLevel类包含对Competency的引用,则无需加入,您可以使用ProficiencyLevel作为查询的根。