Users can have multiple roles. But how can I return all admin users with a List? I tried a similar solution but he had it different compared to mine
USE request_manager; SELECT users
.username
FROM request_manager
.users
JOIN users_roles ON users.id=users_roles.user_id WHERE role_id=2;
This query will return what I need in SQL but I don't know how to make it return it here in springboot. I If there is another better method, I'd be glad to know.
User.java (entity)
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String username;
private String password;
private String name;
private String surname;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")
)
private Set<Role> roles = new HashSet<>();
@OneToMany(mappedBy = "user")
@ToString.Exclude
private List<RequestEntity> requestEntities;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
User user = (User) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return 0;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public void addRole(Role role) {
this.roles.add(role);
}}
Role.java (entity)
@Entity
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(nullable = false, length = 45)
private String name;
public Role() { }
public Role(String name) {
this.name = name;
}
public Role(Integer id, String name) {
this.id = id;
this.name = name;
}
public Role(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}}
UserRepository.java (repo)
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.username = ?1")
User findByUsername(String username);
}
CodePudding user response:
I would suggest trying this:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findAllByRole_Id(Integer roleId);
}