JPA实体
组织实体
@Entity
public class Organization implements Serializable{
private Integer id; // @Id
private String name;
// Getters and Setters
}
放置实体
@Entity
public class Place implements Serializable{
private Integer id; // @Id
private String name;
private Organization organization; // @ManyToOne relation
// Getters and Setters
}
个人资料实体
@Entity
public class Profile implements Serializable{
private String username;// @Id
private Set<VisitedPlace> visitedPlaces; // @OneToMany(mappedBy = "profile")
// Getters and Setters
}
VisitedPlace实体
@Entity
public class VisitedPlace implements Serializable{
private Integer id; // @Id
private Date visitedDate;
private Place place; // @ManyToOne relation
private Profile profile; // @ManyToOne relation
// Getters and Setters
}
这将创建这些表,但我也将使用示例数据显示它
组织表
=====================
| id | name |
-----+----------------+
| 1 | Organization 1 |
=====================
放置表格
=================================
| id | name | organization_id |
-----+----------+-----------------+
| 1 | Place 1 | 1 |
-----+----------+-----------------+
| 2 | Place 2 | 1 |
-----+----------+-----------------+
| 3 | Place 3 | 1 |
=================================
个人资料表
=============
| username |
--------------
| 111@xxx.com |
--------------
| 222@xxx.com |
=============
访问目录表
================================================
| id | visiteddate | place_id | profile_username |
-----+-------------+----------+---------------- -+
| 1 | 2017-01-01 | 1 | 111@xxx.com |
-----+-------------+----------+------------------+
| 2 | 2017-02-01 | 2 | 111@xxx.com |
-----+-------------+----------+------------------+
| 3 | 2017-01-15 | 1 | 111@xxx.com |
================================================
我的问题是如何将下一个本机SQL查询映射到JPQL
SELECT p.username, count(distinct pl.id) FROM profile p LEFT OUTER JOIN visitedplace vp ON p.username = vp.profile_username LEFT JOIN place place ON vp.place_id = pl.id AND pl.organization_id = 1 GROUP BY p.username;
所以我会得到下一个结果
=====================
| username | count |
-------------+-------
| 111@xxx.com | 2 |
-------------+-------
| 222@xxx.com | 0 |
=====================
我一直在尝试下一个JPQL
SELECT profile.username, COUNT( DISTINCT place.id ) FROM Profile profile LEFT OUTER JOIN profile.visitedPlaces visitedPlace LEFT JOIN visitedPlace.place place WHERE place.organization.id = 1 GROUP BY profile.username
但确实会返回
=====================
| username | count |
-------------+-------
| 111@xxx.com | 2 |
=====================
所以我真正的问题是将下一行转换为JPQL
LEFT JOIN place place ON vp.place_id = pl.id AND pl.organization_id = 1
答案 0 :(得分:1)
不幸的是,仅在JPA 2.1规范中支持添加 ON 子句。
所以到目前为止,我们不能将 AND 与 ON 子句一起使用。
您可以从http://download.oracle.com/otndocs/jcp/persistence-2_1-fr-eval-spec/index.html
获取JPA 2.1规范所以,希望我们能在下一个版本中获得它。