【发布时间】:2017-07-05 12:29:58
【问题描述】:
这是我的代码
用户类
@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 将用户正确插入数据库。
【问题讨论】:
-
“这不起作用” 这是什么意思?异常或没有异常但表中也没有数据?如果您有异常堆栈跟踪,请分享。
-
@Rohit 我编辑了这个问题。我的代码不工作。我需要知道如何正确地将用户插入数据库。
-
答案here对你没有帮助吗?
-
@Rohit 没有。因为我应该作为 USERID 传递什么值?如何获取我同时插入的用户的 id?
-
你的用户ID是怎么生成的?
标签: java mysql spring hibernate