如何使用ENUM列出角色?

huangapple go评论77阅读模式
英文:

How do I list roles using ENUM?

问题

以下是您要翻译的内容:

// 用户控制器
private UserRepository userRepository;

public UserController(UserRepository userRepository) {
    this.userRepository = userRepository;
}

@PostMapping
public String userPostAdd(@RequestBody User user) {
    List<Authority> rolesList = new ArrayList<>();
    for (Role role : user.getRole()){
        Authority r = role.getName();
        if (r != null){
            rolesList.add(r);
        }
    }

    if (!rolesList.isEmpty()){
        userRepository.save(user);
    }
    return "添加用户";
}

// 角色实体
@ToString
@Entity
@Table(name = "role", schema = "task")
public class Role {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "name", nullable = false)
@Enumerated(EnumType.STRING)
private Authority name;

@ManyToMany(fetch = FetchType.LAZY, mappedBy = "role")
private List<User> users;

// getter、setter...

}

// 用户实体
@ToString
@Entity
@Table(name = "user", schema = "task")
public class User {

@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@ManyToMany
@JoinTable(name = "user_role",
        joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
private List<Role> role;

@OneToMany(mappedBy = "user")
private Set<Contract> contract;

@Column(name = "surname", nullable = false)
private String surname;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "email", nullable = false, unique = true)
private String email;
@Column(name = "phone", nullable = false, unique = true)
private Integer phone;

// getter、setter...

}

// 枚举
public enum Authority {
    TENANT ("tenant"),
    LANDLORD ("landlord"),
    ADMIN ("admin");

    private final String name;

    private Authority(String s) {
        name = s;
    }

    public boolean equalsName(String otherName) {
        return name.equals(otherName);
    }

    public String toString() {
        return this.name;
    }
}
英文:

Example of a POST request that I will make to add a user: Vasya, Petrenko,910382741, vasya@mail.ru, ADMIN the first 4 attributes work, but I don't understand how to make a field for a role.

Is my database built correctly? I use Json to send a request to add a user, the user's relationship to the role is many to many. I don't understand how to send the role, I need another attribute in the user?

UserController
private UserRepository userRepository;
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@PostMapping
public String userPostAdd(@RequestBody User user) {
List&lt;Authority&gt; rolesList = new ArrayList&lt;&gt;();
for (Role role : user.getRole()){
Authority r = role.getName();
if (r != null){
rolesList.add(r);
}
}
if (!rolesList.isEmpty()){
userRepository.save(user);
}
return &quot;Add user&quot;;
}

Entity Role

@ToString
@Entity
@Table(name = &quot;role&quot;, schema = &quot;task&quot;)
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = &quot;name&quot;, nullable = false)
@Enumerated(EnumType.STRING)
private Authority name;
@ManyToMany(fetch = FetchType.LAZY, mappedBy = &quot;role&quot;)
private List&lt;User&gt; users;
getter,setter...
}

User:

@ToString
@Entity
@Table(name = &quot;user&quot;, schema = &quot;task&quot;)
public class User {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name = &quot;id&quot;)
private Long id;
@ManyToMany
@JoinTable(name = &quot;user_role&quot;,
joinColumns = @JoinColumn(name = &quot;role_id&quot;, referencedColumnName = &quot;id&quot;),
inverseJoinColumns = @JoinColumn(name = &quot;user_id&quot;, referencedColumnName = &quot;id&quot;))
private List&lt;Role&gt; role;
@OneToMany(mappedBy = &quot;user&quot;)
private Set&lt;Contract&gt; contract;
@Column(name = &quot;surname&quot;, nullable = false)
private String surname;
@Column(name = &quot;name&quot;, nullable = false)
private String name;
@Column(name = &quot;email&quot;, nullable = false, unique = true)
private String email;
@Column(name = &quot;phone&quot;, nullable = false, unique = true)
private Integer phone;
getter,setter...
}

Enum

public enum Authority {
TENANT (&quot;tenant&quot;),
LANDLORD (&quot;landlord&quot;),
ADMIN (&quot;admin&quot;);
private final String name;
private Authority(String s) {
name = s;
}
public boolean equalsName(String otherName) {
return name.equals(otherName);
}
public String toString() {
return this.name;
}
}

如何使用ENUM列出角色?

答案1

得分: 1

问题在于你将 roles = null,然后对其进行方法调用。你首先需要通过调用 valueOf 方法来获取角色对象。如果角色不存在,它应该是 null。以下代码应该可以工作。

@PostMapping
public String userPostAdd(@ModelAttribute User user) {
    List<Roles> rolesList = new ArrayList<>();
    for (Role role : user.getRole()){
        Roles r = Roles.valueOf(role.getName().toUpperCase());
        if (r != null){
            rolesList.add(r);
        } 
    }
    
    if (!rolesList.isEmpty()){
       userRepository.save(user);
    } 
    return "Add user";
}
英文:

The problem is that you're setting roles = null and then make a method call on it. You first need to fetch the role object by calling valueOf. If the role does not exist it should be null. The following should work.

@PostMapping
public String userPostAdd(@ModelAttribute User user) {
List&lt;Roles&gt; rolesList = new ArrayList&lt;&gt;();
for (Role role : user.getRole()){
Roles r = Roles.valueOf(role.getName().toUpperCase());
if (r != null){
rolesList.add(r)
} 
}
if (!rolesList.isEmpty()){
userRepository.save(user);
} 
return &quot;Add user&quot;;
}

huangapple
  • 本文由 发表于 2020年9月26日 02:28:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64069571.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定