我在创建父对象和子对象并使用 JPA 和休眠将它们一次性保存到数据库时遇到问题。父类如下所示:
@Entity
@Table(name = "PUser")
public final class User {
@Id
@Column(name = "ID", unique = true, nullable = false, updatable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
}
子对象使用复合键,其中一个字段是父对象的 ID:
@Entity
@Table(name = "PAttribute")
public final class Attribute {
@EmbeddedId
@AttributeOverrides({
@AttributeOverride(name = "domain", column = @Column(name = "domain", nullable = false, length = 128)),
@AttributeOverride(name = "name", column = @Column(name = "name", nullable = false, length = 128)),
@AttributeOverride(name = "userid", column = @Column(name = "userid", nullable = false)) })
private AttributePk pk;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userid", nullable = false, insertable = false, updatable = false)
private User user;
}
复合键类是:
@Embeddable
public class AttributePk implements java.io.Serializable {
private static final long serialVersionUID = -7003721226789641149L;
@Column(nullable = false, length = 128)
private String domain;
@Column(nullable = false, length = 128)
private String name;
@Column(nullable = false)
private long userid;
}
现在当我创建一个新用户并添加一个附件,然后尝试保存对象图
User user = new User("joe1.bloggs@ft.com", "xyz");
user.setScreenName("joe1bloggs");
user.addAttribute("domain", "name", 212);
target.saveAndFlush(user);
我得到了例外
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`fta_portal_user/PAttribute`, CONSTRAINT `userId` FOREIGN KEY (`userid`) REFERENCES `PUser` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
显然 Attribute 子对象没有设置用户对象的 ID。
我知道我可以执行以下操作,但很奇怪,我不能只创建一个对象层次结构,而 Hibernate 会计算出如何相应地设置 ID。我怀疑没有办法解决这个问题,因为 saveAndFlush() 返回一个新实例,而不仅仅是更新输入参数版本。
User user = new User("joe1.bloggs@ft.com", "xyz");
user.setScreenName("joe1bloggs");
// target is an JpaRepository intergafe
user = target.saveAndFlush(user);
user.addAttribute("domain", "name", 212);
target.saveAndFlush(user);
任何人都有任何想法,或者这只是一个与之共存的案例?
谢谢
缺口
编辑:您可以通过将 @MapsId 注释添加到子类来使其工作(感谢 axtavt 的回复)。IE
@MapsId("userId")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userId", nullable = false, insertable = false, updatable = false)
private User user;