Hibernate 5.2 Criteria Query(Join),选择特定列

时间:2016-08-24 13:43:48

标签: java mysql hibernate hibernate-mapping

美好的一天,我的问题将由两部分组成。所以,我有3个表:

A ABC CD

我想知道如何使用hibernate CriteriaQuery 实现以下查询:

SELECT DISTINCT a
FROM a
LEFT JOIN abc ON a.Id = abc.a_Id
LEFT JOIN cd ON cd.c_Id = abc.c_Id
WHERE a.name = "foo" or cd.name = "bar"

这一个(查询相同,但在这种情况下,我希望只有一列而不是完整行结果):

SELECT DISTINCT a.Id
FROM a
LEFT JOIN abc ON a.Id = abc.a_Id
LEFT JOIN cd ON cd.c_Id = abc.c_Id
WHERE a.name = "foo" or cd.name = "bar"

1 个答案:

答案 0 :(得分:0)

这里有一个简单的方法:

public List<MyObject> listeOfMyObject() {
    EntityManager em;
    try {
        em = getEntityManager();
        Query query = em.createQuery("SELECT DISTINCT a FROM MyObject a LEFT JOIN abc ON a.Id = abc.a_Id LEFT JOIN cd ON cd.c_Id = abc.c_Id WHERE a.name = 'foo' or cd.name = 'bar'");
        return query.getResultList();
    } catch (Exception e) {
        return null;
    }
}

如果您使用的是参数,请使用:

public List<MyObject> listeOfMyObject() {
    EntityManager em;
    try {
        em = getEntityManager();
        Query query = em.createQuery("SELECT DISTINCT a FROM MyObject a LEFT JOIN abc ON a.Id = abc.a_Id LEFT JOIN cd ON cd.c_Id = abc.c_Id WHERE a.name = :a_name or cd.name = :cd_name");
        //set your parametres like that
        query.setParameter("c_name", "foo");
        query.setParameter("cd_name", "bar");
        return query.getResultList();
    } catch (Exception e) {
        return null;
    }
}

如果您只想获得一个结果:

public MyObject myObject() {
    EntityManager em;
    try {
        em = getEntityManager();
        Query query = em.createQuery("SELECT DISTINCT a FROM MyObject a LEFT JOIN abc ON a.Id = abc.a_Id LEFT JOIN cd ON cd.c_Id = abc.c_Id WHERE a.name = :a_name or cd.name = :cd_name");
        //set your parametres like that
        query.setParameter("c_name", "foo");
        query.setParameter("cd_name", "bar");
        return (MyObject) query.getSingleResult();
    } catch (Exception e) {
        return null;
    }
}

希望这可以帮到你。