保存子项不应导致在父表中插入行

时间:2016-11-09 13:49:20

标签: java hibernate jpa foreign-keys spring-data-jpa

我在使用@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建立单向关系,但它无济于事。

0 个答案:

没有答案