本文共 1833 字,大约阅读时间需要 6 分钟。
Hibernate创建一对一关系时两张表主表保持一致则可以实现自动新增和删除
@Entity@Table(name = "sys_user")public class User { @Id @GeneratedValue(strategy = IDENTITY) private Long id = new Long(0); @OneToOne(cascade = { CascadeType.ALL}, mappedBy = "user", fetch = FetchType.LAZY) @JsonIgnore private UserAccount userAccount; public UserAccount getUserAccount() { return userAccount; } public void setUserAccount(UserAccount userAccount) { this.userAccount = userAccount; }}
@Entity@Table(name = "sys_user_account")public class UserAccount { @Id @GeneratedValue(generator = "generator") @GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "user")) private Long id = 0L; @OneToOne(fetch = FetchType.LAZY) @PrimaryKeyJoinColumn private User user; public UserAccount() { } public UserAccount(User user) { this.user = user; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public User getUser() { return user; } public void setUser(User user) { this.user = user; }}
public void save(User user) { if (user.isNew()) { user.setUserAccount(new UserAccount(user)); super.save(user); } else { super.save(userModel); }}