如何使用ENUM列出角色?

问题描述

我将添加用户的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",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

解决方法

问题是您要设置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";
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...