我在使用@OneToMany
和@ManyToOne
建立的两个实体之间建立了父子关系。子进程使用父进程的id作为外键和复合主键的一部分。对我来说,持久保存其父级未持久化的子类的实例违反外键约束似乎是合乎逻辑的。我期待一个异常,但我注意到保存子导致父对象也插入数据库。我该如何防止这种情况?
这是父类:
@Entity
public class User {
@GeneratedValue
@Id
private long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "owner")
private List<OneTimeKey> preKeys;
@Lob
private byte[] key;
public User(byte[] key) {
this.key = key;
}
}
儿童班:
public class KeyId implements Serializable {
long owner;
long keyId;
}
@Entity
@IdClass(KeyId.class)
public class OneTimeKey {
@Id
@ManyToOne
private User owner;
@Id
private long keyId;
@Lob
private byte[] key;
public OneTimeKey(User owner, long keyId, byte[] key) {
this.owner = owner;
this.keyId = keyId;
this.key = key;
}
}
这是失败的测试方法:
@Test
public void givenUserDoesntExistShouldNotPersist() {
User testUser = new User("owner".getBytes());
OneTimeKey preKey = new OneTimeKey(testUser, 0, "test".getBytes());
oneTimeKeyRepository.saveAndFlush(preKey);
OneTimeKey result = oneTimeKeyRepository.findOne(new KeyId(1, 0));
assertNull(result);
}
日志显示调用saveAndFlush()会导致:
Hibernate: insert into User (key, id) values (?, ?)
Hibernate: insert into OneTimeKey (key, keyId, owner_id) values (?, ?, ?)
我尝试使用@JoinColumn
建立单向关系,但它无济于事。