当用户在 Spring Security 中注册时,我尝试添加默认角色值。
我有两个模型“用户”和“角色”,以多对多关系链接。
用户.java
@NotEmpty
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Role> roles = new HashSet<>();
角色.java
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(length=15, unique=true, nullable=false)
private String role = RoleType.USER.getRole();
数据.sql
INSERT INTO ROLE(role) VALUES ('USER');
INSERT INTO USER(email,password) VALUES ('user@mail.com','user');
INSERT INTO USER_ROLES(user_id, roles_id) VALUES (1,1);
这里的想法是使用 role_id 来设置用户角色,但我更喜欢使用字符串来实现方便。像这样的一两行内容
INSERT INTO USER_ROLES(user_id, roles) VALUES (1, "ADMIN");
INSERT INTO USER_ROLES(user_id, roles) VALUES (1, "DBA");
此外,当我尝试从 JAVA 创建用户时,我需要使用角色 dao 来检索相应的 id,并且我想默认将新用户设置为“ROLE_USER”。
UserDBTest.java
@Before
public void setUp() {
User user = new User();
user.setEmail("email@mail.com");
user.setPassword("password");
user.addRole(roleRepository.findOne(1L)); //detached entity passed to persist
user = userRepository.save(user);
}
最佳答案
您可以这样编写 SQL:
INSERT INTO USER_ROLES(user_id, roles)
VALUES (1, (SELECT id FROM roles WHERE role='ADMIN'));
您遇到的 JPA 错误是因为您没有在事务中运行。 例如,如果您使用 TestNG,您可以让您的测试类扩展 AbstractTransactionalTestNGSpringContextTests
,并且它将起作用。
更新:如果需要额外的数据库查找,可以选择将角色名称直接存储在 USER_ROLES
表中,User.java 将如下所示:
@ElementCollection
@Enumerated(EnumType.STRING)
private Set<RoleType> roles;
关于java - 用户角色的默认值 - Spring security,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35405527/