让我们考虑两个实体:
@Entity
@Table
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user")
private UserDetails userDetails;
}
@Entity
@Table(name="user_details")
public class UserDetails {
@GenericGenerator(name = "generator", strategy = "foreign",
parameters = @Parameter(name = "property", value = "user"))
@Id
@GeneratedValue(generator = "generator")
@Column(unique = true, nullable = false)
private Integer id;
@OneToOne
@PrimaryKeyJoinColumn
private User user;
public UserDetails(User user) {
this.user = user;
user.setUserDetails(this);
}
}
并给出代码行:
UserDetails details = new UserDetails(user);
session.merge(details);
产生错误:
org.springframework.orm.jpa.JpaSystemException: attempted to assign id from null one-to-one property [com.app.domain.UserDetails.user]; nested exception is
org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.app.domain.UserDetails.user]
我知道,当我使用方法save()而不是merge()时,它会起作用。但是,ethod save()不能自动更新现有的行,而merge()可以。