如何通过CriteriaBuilder从实体中选择Set <>属性

时间:2019-05-09 12:36:51

标签: jpa eclipselink criteria

我有这个实体:

public Entity {

    @JoinTable(name = "entity_equivalents",
            joinColumns = {
                @JoinColumn(name = "entity_new")},
            inverseJoinColumns = {
                @JoinColumn(name = "entity_old")})
    @OneToMany
    private Set<Entity> equivalents;

我一直试图创建一个CriteriaQuery,从实体中选择等效项,但我不知道如何创建CriteriaQuery

  public Set<Entity> findEquivalents(Entity p1) {
        EntityManager em = getEntityManager();
        CriteriaBuilder cb = em.getCriteriaBuilder();
    // HERE is the problem
        CriteriaQuery<Set<Entity>> query = cb.createQuery(); // <----
        Root<Entity> root = query.from(Entity.class);
        Expression<Set<Entity>> exx= root.get(Entity_.equivalents);
        query.select(exx); 
        query.where(cb.equal(root.get(Entity_.id), p1.getId()));
        return em.createQuery(query).getSingleResult();

    }

在使用FetchType.EAGER之类的实例时,我不想设置属性enti.getEquivalents();或让EM打开并获取负载

临时解决方法(直到有人引导我揭示CriteriaQuery的奥秘):

return new HashSet<>(getEntityManager()
.createQuery("SELECT o.equivalents from Entity o where o.id=" + id)
.getResultList());

0 个答案:

没有答案