Spring Data JPA - 使用@Query与多对多关系/连接表

时间:2018-05-22 15:15:42

标签: java spring spring-data spring-data-jpa

我有一个与角色实体有多对多关系的用户实体。

    @Entity
@Table(name = "auth_user")
public class OAuthUser {

    // @Autowired
    // @Transient
    // private PasswordEncoder passwordEncoder;
    //
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "username")
    private String userName;

    @Column(name = "password")
    @JsonIgnore
    private String password;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "email")
    private String email;

    @Column(name = "is_enabled")
    private boolean isEnabled;

    /**
     * Reference:
     * https://github.com/nydiarra/springboot-jwt/blob/master/src/main/java/com/nouhoun/springboot/jwt/integration/domain/User.java
     * Roles are being eagerly loaded here because they are a fairly small
     * collection of items for this example.
     */
    @ManyToMany(fetch = FetchType.EAGER)
    @Fetch(value = FetchMode.SUBSELECT)
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
    private List<Role> roles;

    @ManyToMany(fetch = FetchType.EAGER)
    @Fetch(value = FetchMode.SUBSELECT)
    @JoinTable(name = "user_properties", joinColumns = @JoinColumn(name = "AuthID", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "PropertyID", referencedColumnName = "id"))
    private List<Property> properties;

我正在使用Spring Data JPA存储库,并且能够创建一个自定义@Query,它根据特定的角色ID返回用户列表。

    @Query("SELECT u FROM auth_user as u WHERE u.isEnabled AND u.id IN"
        + " (SELECT r.user_id FROM user_role as r WHERE r.role_id = ?1)")
public List<OAuthUser> findByRole(int roleID);

上面的代码会导致错误auth_user is not mapped。我明白为什么我得到错误;框架使用实体名称(OAuthUser)而不是表(auth_user)来执行查询。这通常不是问题,除了user_role没有实体;它只是一个包含两列的联接表:&#39; user_id&#39;和&#39; role_id&#39;。

实现这一目标的适当方法是什么?

感谢。

2 个答案:

答案 0 :(得分:1)

错误说:

  

未映射auth_user

它指的是查询中使用的auth_user,如SELECT u FROM auth_user。在查询中,它必须是OAuthUser

答案 1 :(得分:1)

您正在使用jpql @Query中的表名(auth_user)。您应该使用班级名称 OAuthUser

ABS

如果要使用SQL而不是jpql,则需要使用如下:

SELECT DATEDIFF(DAY,'20180522','20180520'), --returns -2
       ABS(DATEDIFF(DAY,'20180522','20180520')); --returns 2

这样你可以提到表名和列。