我有一个与角色实体具有多对多关系的用户实体。
@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
,该@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
没有实体;它只是一个包含两列的连接表:‘user_id’和‘ole_id’。
实现这一目标的适当方式是什么?
谢谢。
2条答案
按热度按时间vnjpjtjt1#
错误是这样说的:
未MapAUTH_USER
它指的是查询中使用的
auth_user
,如SELECT u FROM auth_user
。在查询中,它必须改为OAuthUser
。pgccezyw2#
您在jpql@Query中使用了表名(Auth_User)。您应该改用类名OAuthUser:
如果您想使用SQL而不是jpql,您需要这样使用:
这样,您就可以提到表名和列。