我的Spring MVC应用程序具有一个具有USER_ROLES n的域USER
public class User {
...
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.DETACH})
@JoinTable(name = "L_USER_ROLE", catalog = "PUBLIC", joinColumns = {
@JoinColumn(name = "fk_user", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "fk_role",
nullable = false, updatable = false) })
private List<UserRole> hasRoles;
...
}
在JSP页面中,可以编辑用户,也可以将User_Roles分配给用户。
user.jsp
<div class="form-group">
<label class="col-sm-2 control-label" for="hasRoles">Roles</label>
<!-- Test to see, if the user has roles (this part displays the correct Roles -->
<c:forEach items="${userObj.hasRoles}" var="role">
${role.role}<br>
</c:forEach>
<!-- here the existing roles should be highlighted, but this does not work -->
<div class="col-sm-7">
<form:select path="hasRoles" items="${userRoles}" multiple="true" itemValue="id" itemLabel="role" class="form-control input-sm" />
<div class="has-error">
<form:errors path="hasRoles" class="help-inline"/>
</div>
</div>
</div>
我没有显示控制器,因为实际上编辑角色分配可以正常工作。我还可以看到,jsp中提供了hasRoles集合。 唯一的问题是,在我的可用角色列表中,当前分配的角色未突出显示。
@Entity
@Table(name = "USER_ROLES", catalog = "PUBLIC", uniqueConstraints = {
@UniqueConstraint(columnNames = "ROLE"),
})
public class UserRole {
@Id
@GeneratedValue
private int id;
private String role;
@Override
public boolean equals(Object that) {
UserRole thatRole = (UserRole)that;
if (thatRole.role == null || this.role == null)
return false;
return this.role.equals(thatRole);
}
@Override
public int hashCode() {
return this.role.hashCode();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}