Issue
I have a User entity with a many-to-many relationship with a Role entity.
@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;
I am using the Spring Data JPA repositories, and would to be able to create a custom @Query
that returns a list of users based upon a particular role 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);
The code above results in the error auth_user is not mapped
. I do understand why I am getting the error; the framework is using the entity names (OAuthUser) rather than the table (auth_user) to perform the query. This would ordinarily not be a problem, except for there is no entity for user_role
; it is simply a join table with two columns: 'user_id' and 'role_id'.
What is the appropriate way to achieve this?
Thanks.
Solution
The error says:
auth_user is not mapped
It refers to the auth_user
used in the query like SELECT u FROM auth_user
. It must be OAuthUser
instead, in the query.
Answered By - Bhesh Gurung
Answer Checked By - Willingham (JavaFixing Volunteer)