这是我的代码
用户类别
@Entity
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private String username;
@OneToMany(fetch=FetchType.EAGER)
@JoinColumn(name="APP_USER_ID", referencedColumnName="id")
private List<UserRole> roles;
@Column
private String email;
@Column
private String password;
protected User(){
}
public User(String username, String email, String password, List<UserRole> roles){
this.username = username;
this.email= email;
this.password= password;
this.roles= roles;
}
用户角色类
@Entity
@Table(name = "user_role")
public class UserRole {
@Embeddable
public static class Id implements Serializable {
private static final long serialVersionUID = 1322120000551624359L;
@Column(name = "APP_USER_ID")
protected Integer userId;
@Enumerated(EnumType.STRING)
@Column(name = "ROLE")
protected Role role;
public Id() { }
public Id(Integer userId, Role role) {
this.userId = userId;
this.role = role;
}
}
@EmbeddedId
Id id = new Id();
@Enumerated(EnumType.STRING)
@Column(name = "ROLE", insertable=false, updatable=false)
protected Role role;
public Role getRole() {
return role;
}
}
这些是数据库中的表
- 用户表 -> |编号 |电子邮件 |密码 |用户名 |
- user_role 表 -> |角色 | APP_USER_ID |
在此项目中,一个用户可以拥有多个角色。 在我的服务类中,我试图像这样保存用户(下面的代码不起作用,它更像是伪代码,但根据我目前的理解,我觉得我应该遵循这种方法),
return userRepository.save(new User(username, email, encoder.encode(password)),
new List<UserRole>(){{
add(//create a new UserRole...);
}}));
我对 spring/hibernate 不太熟悉,我不知道如何使用 hibernate 将用户正确插入数据库。
最佳答案
UserRole
类没有任何接受任何参数的构造函数,因此您不能编写:new UserRole(USERID,"ADMIN")
,但是您可以想要通过内部类Id
创建一个userId
,所以可能你需要这样写:new UserRole.Id(USERID,"ADMIN")
.
关于java - 当存在@Embeddable ID时如何正确插入@Entity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44926349/