java - 用户角色的默认值 - Spring security

标签 java sql spring spring-security

当用户在 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/

相关文章:

mysql - SQL 查询左连接问题

SQL - 获取昨天和前天的数据

SQL 按一列分组,计算另一列中的条目

java - 未找到引用的 bean 'name'

java - 由于 'org.hibernate.HibernateException: No Session found for current thread' 异常,需要 @Transactional 注释

java - Spring Data Jpa 无需 @Query 即可连接多个表

java - JSch SFTP 传输更改编码

java - Selenium 2 驱动程序.findElement()

java - 有效的Java。可克隆界面

java - 尝试在 Recyclerview 中实现 ONClickListener 时出错