我有一对一的映射关系。
User.java
public class User {
@Id
@SequenceGenerator(name = "userID", sequenceName = "userID")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "userID")
@Column(name = "id")
private Long id;
private String firstName;
private String lastName;
@Column(unique = true)
private String username;
private String password;
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "id")
private Role role;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
@Override
public String toString() {
return "User [id=" + id + ", firstName=" + firstName + ", lastName="
+ lastName + ", username=" + username + ", password="
+ password + ", role=" + role + "]";
}
}
Roles.java
public class Role {
@Id
@SequenceGenerator(name = "userID", sequenceName = "userID")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "userID")
@Column(name = "roleId")
private Long roleId;
@OneToOne
private User user;
private Integer role;
public Long getId() {
return roleId;
}
public void setId(Long id) {
this.roleId = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
}
我想保存数据
public Long create(User user) {
Long userID = super.save(user);
return userID;
}
当我尝试保存用户实体时,我看到数据保存如下。
用户表:
id firstName lastName usrename password
1 hello hello hello hello
角色表:
roleId role user_id
1 1 NULL
你能告诉我你的用户表没有相互关联吗?
我需要user_id为1而不是NULL。
此处用户表的id未映射到表Role的user_id。
答案 0 :(得分:0)
角色是协会的所有者,用户的@OneToOne角色根本不需要@JoinColumn:
@Id
@SequenceGenerator(name = "userID", sequenceName = "userID")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "userID")
@Column(name = "id")
private Long id;
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Role role;
保存用户时,您还需要设置关联的两侧:
user.setRole(role);
role.setUser(user);
userDao.create(user);