如何使用 JPA 2.0 从对象内的 2 个表中查询特定列?

How can I query specific columns from 2 tables inside my objects using JPA 2.0?

我正在寻找一种方法来请求特定列并使用 CriteriaBuilder 在根对象中存在外部对象。这是上下文: 我有实体A

@Entity
@Table(name = "ENTITY_A")
public class EntityA {
    int id;
    int entityBKey;
    EntityBObject entityBObject;
    int AColumn1;
    int AColumn2;

    @Basic
    public Long getEntityBKey() {
        return entityBKey;
    }

    @ManyToOne
    @JoinColumn(name = "ENTITY_B_FK")
    public EntityBObject getProgramType() {
        return entityBObject;
    }

    @Basic
    @Column(name = "COLUMN_1")
    public String getAColumn1() {
        return AColumn1;
    }
    ...
}

然后我有EntityB

public class EntityB {
    int id;
    int BColumn1;
    int BColumn2;
    ...
}

现在,我想请求 EntityA 的 AColumn1 列和 EntityB 的 BColumn1 列,同时在 EntityA 中包含对象 EntityB。我怎样才能做到这一点?

如何修改以下内容以获取内部包含 EntityB 的部分 EntityA?

public List<EntityA> findAll() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<EntityA> criteria = cb.createQuery(EntityA.class);
    Root<EntityA> root = criteria.from(EntityA.class);
    criteria.select(root);

    return em.createQuery(criteria).getResultList(); 
}

谢谢!

编辑 @Tassos Bassoukos 是的,这就是我最终所做的,但是当请求变得更复杂时它会变得非常混乱。例如:拉取客户的订单,每个订单的项目。要实现这一点会有很多 java,我虽然它可以自动化,所以我的对象会自动填充。

public List<EntityA> findAll() {
    ArrayList<EntityA> result = new ArrayList<>();
    Query q = em.createQuery("select eA, eB, from EntityA eA, EntityB eB where eA.key = eB.key");

    @SuppressWarnings("unchecked")
    List<Object[]> abc = q.getResultList();
    for (Object[] array : abc) {
        EntityA eA = (EntityA) array[0];
        EntityB eB = (EntityB) array[1];
        eA.setEntityB(eB);
        result.add(pe);
    }

    return result;
}

首先,为什么要部分实体?从面向对象的角度来看,这没有意义。对此有实际的具体要求吗?

其次,您想要实体还是实体列?您可以使用 CriteriaBuilder 来完成这两项操作,但您需要明确 a) 您想要实现的目标,b) 为什么要实现它。

第三,JOIN FETCH