将JPQL转换为QueryDSL

时间:2014-08-26 00:59:30

标签: java mysql jpql querydsl

我在将以下方法转换为QueryDSL时遇到问题,非常感谢一些反馈!

javax.persistence.TypedQuery<Long> query = em().createQuery(
        "SELECT COUNT( DISTINCT b ) " +
                "FROM Project a " +
                "JOIN a.projectParticipants b " +
                "WHERE a.projectType IN :projectTypes " +
                "AND a.projectStatus = :projectStatus", Long.class
);
query.setParameter("projectTypes", filter.getProjectTypes());
query.setParameter("projectStatus", ProjectStatus.ACTIVE);
return query.getSingleResult();

项目类:

public class Project {

    @ManyToMany
    @JoinTable(name = "project_user", inverseJoinColumns = @JoinColumn(name = "user_id"))
    private Set<User> projectParticipants = new TreeSet<>();

}

表示项目projectParticipation集的project_user表:

CREATE TABLE IF NOT EXISTS `project_user` (
  `user_id` bigint(20) NOT NULL,
  `project_id` bigint(20) NOT NULL,
  PRIMARY KEY (`user_id`,`project_id`),
  KEY `project_user_project_id` (`project_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

1 个答案:

答案 0 :(得分:2)

以下内容应该有效

query.from(a)
  .join(a.projectParticipants, b)
  .where(a.projectType.in(projectTypes), a.projectStatus.eq(projectStatus))
  .singleResult(b.countDistinct());