连接表查询:表未映射

时间:2016-12-11 15:34:23

标签: mysql sql spring jpa spring-boot

我有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

欢迎提出任何建议,谢谢

1 个答案:

答案 0 :(得分:1)

JPQL是围绕关系构建的,因此只需沿着关系导航,以包含您想要设置约束的任何实体。所以,像

SELECT t FROM Task t JOIN t.collaborators c JOIN c.user u JOIN u.roles r
WHERE r.name = :role AND t.done = :done

因此,您不会引用任何“连接表”,这只是一个持久性构造,与查询无关。