JPA / Hibernate查询只返回一行

时间:2016-09-14 19:08:23

标签: mysql sql hibernate jpa

我正在使用JPA2 / Hibernate5和Java8而不是MySql。

我运行以下原生查询:

Query q = entityManager.createNativeQuery(sb.toString(), JobWithDistance.class);
q.setParameter("ids", ids);
List<JobWithDistance> jobsWD = (List<JobWithDistance>) q.getResultList();

当我使用相同的参数直接对数据库运行时,sb中的sql返回 3行。但是,当我通过Hibernate运行本机查询时,我只能一行

为什么结果不同?

更多信息:

Hibernate返回1行:

    StringBuilder sb = getFindQuery();
    sb.append("  where e.id in (:ids) ");
    Query q = entityManager.createNativeQuery(sb.toString(), JobWithDistance.class);
    q.setParameter("ids", ids);
    //Object o = q.getResultList();
    List<JobWithDistance> jobsWD = q.getResultList();

private StringBuilder getFindQuery() {
    StringBuilder sb = new StringBuilder();
    sb.append(" select * ");
    sb.append(" , -1 as noReviews, -1 as averageRating ");
    sb.append(" , -1 AS distance ");
    sb.append(" from ");
    sb.append("    www.job as e ");
    sb.append(" inner join www.person_job as pj on e.id = pj.JOB_ID ");
    sb.append(" inner join www.person as p on pj.PER_ID = p.id ");
    sb.append(" left join www.rating_job rp ON e.id = rp.JOB_ID ");
    sb.append(" left join www.rating r ON rp.RAT_ID = r.id ");
    return sb;
}

对数据库运行时,以下SQl返回3行:

 select *  , -1 as noReviews, -1 as averageRating  , -1 AS distance  from     www.job as e  inner join www.person_job as pj on e.id = pj.JOB_ID  inner join www.person as p on pj.PER_ID = p.id  left join www.rating_job rp ON e.id = rp.JOB_ID  left join www.rating r ON rp.RAT_ID = r.id   where e.id in (65, 66, 64) 

由于

1 个答案:

答案 0 :(得分:0)

解决方案:

@Override
public List<Job> findById(String ids) {

    String[] args = ids.split(",");
    Set<String> idSet = new HashSet<String>(Arrays.asList(args));

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Job> query = builder.createQuery(Job.class);
    Root<Job> post = query.from(Job.class);
    query.select(post).where(post.get("id").in(idSet)); // or pass a tag collection to `in` method
    TypedQuery<Job> typedQuery = entityManager.createQuery(query);
    List<Job> results = typedQuery.getResultList();
    return results;
}