如何解决JPA - 休眠 - 一对一
我在表 User 和 Profile 之间有一个 OneToOne 关系,定义如下:
@Entity
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name="users",uniqueConstraints = {
@UniqueConstraint(columnNames = "username"),@UniqueConstraint(columnNames = "email")
}
)
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int idUser;
private String username;
private String email;
private String password;
@OneToOne(cascade=CascadeType.ALL,orphanRemoval=true)
@JoinColumn(name="id_profile",referencedColumnName="idProfile")
private Profile profile;
@ManyToMany(fetch = FetchType.EAGER)
private Set<Role> roles = new LinkedHashSet<Role>();
}
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name="profile",uniqueConstraints = @UniqueConstraint(columnNames = "discordId")
)
public class Profile implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int idProfile;
private Date birthday;
private String discordId;
private String description;
@ElementCollection(fetch=FetchType.EAGER)
private Set<String> spokenLanguages = new LinkedHashSet<String>();
@OneToMany(fetch=FetchType.EAGER)
private Set<ProfileGame> profileGames = new LinkedHashSet<>();
@OneToOne(mappedBy="profile")
private User user;
@ManyToOne
private TimeSlot timeSlot;
}
然后我运行一个测试在我的数据库中创建一些夹具:
Profile profile = this.profileRepository.save(Profile.builder()
.birthday(new Date())
.discordId("discord-" + i)
.description("Description de user-" + i)
.spokenLanguages(spokenLanguages)
.timeSlot(timeSlot)
.build());
user.setProfile(profile);
System.err.println(user);
这里一切正常,System.err.println(user) 返回正确的值。
问题来自数据库,它没有“应用”我的用户表中的 id_profile:
我错过了什么?
解决方法
尝试做这样的事情:
Profile profile = Profile.builder()
.birthday(new Date())
.discordId("discord-" + i)
.description("Description de user-" + i)
.spokenLanguages(spokenLanguages)
.timeSlot(timeSlot)
.user(user)
.build();
user.setProfile(profile);
profile = this.profileRepository.save(profile);
您使用双向 @OneToOne
关联,因此您应该确保双方始终保持同步。
此外,由于您需要将持久状态传播给用户,您应该将 cascade = CascadeType.ALL
添加到 Profile.user
中,如下所示:
@Entity
public class Profile implements Serializable {
// ...
@OneToOne(mappedBy="profile",cascade=CascadeType.ALL)
private User user;
}
,
类用户:
@OneToOne(mappedBy = "user",cascade = CascadeType.ALL,fetch = FetchType.LAZY,optional = false)
private Profile profile;
班级简介:
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="id_user")
private User user;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。