【问题标题】:Spring data rest, default value for relationship propertySpring数据休息,关系属性的默认值
【发布时间】:2018-05-19 11:29:32
【问题描述】:

我有用户和权限实体,连接多对多关系。 当我使用 POST 添加新用户时,我想为他设置默认角色,例如存在“admin”的角色。我不想手动执行此操作。

@Data
@Entity
public class User {

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

@Column(unique = true)
@NotNull
private String username;

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_authority", joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
        inverseJoinColumns = {@JoinColumn(name = "authority_id", referencedColumnName = "id")})
private List<Authority> authorities;

}

我该怎么做?我知道如何为用户名设置默认值,但是当它有关系时我不知道该怎么做。

感谢您的帮助

【问题讨论】:

标签: spring hibernate jpa jwt spring-data-rest


【解决方案1】:

我认为你可以用纯 java 实现这一点:

private List<Authority> authorities = Arrays.asList(Authority.ADMIN);

因此,例如,您拥有枚举 Authority,并且您将在系统中创建的每个 User 对象默认具有 ADMIN 作为权限。那么当你保存用户时,它的权限也会被保存。

【讨论】:

  • 感谢您的帮助,但是我怎样才能分配实际存在的对象,例如 authorityRepository findByName('ROLE_USER') 返回我想默认分配的对象,可以吗?
  • 你可以在构造函数中实现这个逻辑,例如。创建列表 -> 查找所需内容 -> 将项目添加到列表中 -> 将列表分配给字段。
猜你喜欢
  • 2015-09-16
  • 1970-01-01
  • 2013-04-23
  • 2011-09-16
  • 2016-10-07
  • 2016-04-22
  • 1970-01-01
  • 2015-05-23
  • 2016-05-31
相关资源
最近更新 更多