如何获取springboot中具有角色的所有用户的列表



我有3个表(用户(id_User…(-角色(id_Role(-用户角色(id_Role,id_User((manytomy((。我想得到所有UserRoles的列表。

//服务

public List<User> AllUsers() {
return loginRepo.findAll();
}

//控制器

@GetMapping("/gestion_utilisateurs")
public String GetAllUsers(Model model) {
List<User> all_users = loginServ.AllUsers();
model.addAttribute("all_users", all_users);
return "administration/identite_patient/gestion_utilisateurs";
}

//查看

<th:block th:each="all_users : ${all_users}">
<tr>
<td th:style = "${all_users.enabled == true } ? 'color: green' : 'color: red' " > &diams; </td>
<td th:text="${all_users.nom}"></td>
<td th:text="${all_users.prenom}"></td>
<td th:text="${all_users.username}"></td>
<td th:text="${all_users.roles.role_name}" ></td>
<td></td>
</tr>
<th:block>

//用户

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "users", uniqueConstraints = @UniqueConstraint(columnNames = "username"))
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Integer id;
private String nom;
private String prenom;
private String username;
private String password;
private boolean enabled;


@ManyToMany(cascade = CascadeType.ALL ,fetch = FetchType.EAGER)
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")
)


//private Collection<Role> roles = new HashSet<>();
private List<Role> roles=new ArrayList<Role>(); 

public User(String nom, String prenom, String username, String password,Boolean enabled, List<Role> roles) {
super();
this.nom = nom;
this.prenom = prenom;
this.username = username;
this.password = password;
this.enabled = true;
this.roles = roles;
}






}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "role_id")
private Long id;
private String role_name;

public Role(String role_name) {
this.role_name = role_name;
}




}

我想显示角色名称,但我不知道如何获取(all_users.roles.role_name不起作用(。如果有人有主意,请帮忙。

由于一个user中可以有多个roles,因此需要像使用all_users一样对它们进行迭代,以列出所有用户。因此,大致如下:

<th:block th:each="all_users : ${all_users}">
<tr>
<td th:style = "${all_users.enabled == true } ? 'color: green' : 'color: red' " > &diams; </td>
<td th:text="${all_users.nom}"></td>
<td th:text="${all_users.prenom}"></td>
<td th:text="${all_users.username}"></td>
<td th:text="${all_users.roles.role_name}"></td>
<td th:each="role : ${all_users.roles}">
<span th:text="${role.role_name}">
</td>
<td></td>
</tr>
<th:block>

最新更新