如何使用ENUM列出角色?

时间:2020-09-25 18:28:41

标签: java spring-boot hibernate

我将添加用户的POST请求示例:Vasya, Petrenko,910382741, vasya@mail.ru, ADMIN前4个属性有效,但我不知道如何为角色创建字段。

我的数据库构建正确吗?我使用Json发送一个添加用户的请求,该用户与角色的关系是多对多的。我不知道如何发送角色,我需要用户中的另一个属性吗?

UserController

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 "Add user";
}

实体角色

@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;
    }
}

enter image description here

1 个答案:

答案 0 :(得分: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";
}