【发布时间】:2017-04-26 13:15:09
【问题描述】:
我有 4 个实体和一个连接表,我想进行这样的查询:
合作者:
@Entity
public class Collaborator implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(cascade = {CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH },
fetch = FetchType.EAGER)
@JoinColumn(name = "UserID", nullable = true)
private User user;
@ManyToOne(cascade = {CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH },
fetch = FetchType.EAGER)
@JoinColumn(name = "TaskID", nullable = true)
private Task task;
...}
用户:
@Entity
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(cascade = {CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH },
fetch = FetchType.EAGER)
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
private Set<Role> roles = new HashSet<>();
OneToMany(mappedBy="user", fetch = FetchType.EAGER)
private Set<Collaborator> collaborators = new HashSet<>();
...}
角色:
@Entity
public class Role implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Column(name = "name", nullable = false)
private String name;
@JsonIgnore
@ManyToMany(mappedBy = "roles",fetch = FetchType.EAGER)
private Set<User> users;
... }
任务:
@Entity
public class Task implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "task", fetch = FetchType.EAGER)
private Set<Collaborator> collaborators = new HashSet<>();
...}
我的问题:
我想按角色获取任务吗?我试过这个查询:
@Query("select t from Task as t, Collaborator as c, Role as r, User as u, users_roles as ur "
+ "where c.user = u.id "
+ "and u.id = ur.user_id "
+ "and r.id = ur.role_id "
+ "and r.name = :role "
+ "and c.task = t.id "
+ "and t.done = :done ")
List<Task> getTasksByRoleAndState(@Param("role")String role, @Param("done") boolean done);
但我得到一个错误:
users_roles is not mapped
欢迎提出建议,谢谢
【问题讨论】:
-
所以你没有实体名为“users_roles”,因为消息说得很清楚。和 ?在 JPQL 中,您可以跨关系使用 JOIN。您不发布您的课程,那么任何人都如何建议要进行哪些 JOIN? JPQL != SQL
-
这个不需要我的类,另外我提到我有 4 个实体和 1 个可连接(很明显我有一个多对多关系),我还提到了连接表链接角色和用户实体。
-
我的一个问题可能是:如何从 JPQL 访问连接表
-
您使用实体的关系。连接表包含不在实体和实体关系中的任何内容。您还没有发布实体,显示关系字段
-
好的,我已经更改了我的帖子,如果你可以看一下。
标签: mysql sql spring jpa spring-boot