JPA+Hibernate:@OneToOne级联保存无效

创建HUSBAND表

CREATE TABLE HUSBAND (
    ID INTEGER,
    NAME VARCHAR2(10) 
);

创建WIFE表

CREATE TABLE WIFE (
    ID INTEGER,
    NAME VARCHAR2(10) 
);

HUABAND实体及Repository

@Entity
@Table(name = "HUSBAND", schema = "SYSTEM")
public class Husband {
    @Id 
    @Column(name = "ID")
    private int id;
    @Column(name = "NAME")
    private String name;
    @OneToOne
    @Cascade({CascadeType.SAVE_UPDATE})
    @PrimaryKeyJoinColumn
    private Wife wife;
    // 省略getter、setter及构造函数
}
public interface HusbandRepository extends JpaRepository<Husband, Integer> {
}

WIFE实体及Repositpry

@Entity
@Table(name = "WIFE", schema = "SYSTEM")
public class Wife {
    @Id 
    @Column(name = "ID")
    private int id;
    @Column(name = "NAME")
    private String name;
    @OneToOne
    @PrimaryKeyJoinColumn
    private Husband husband;
    // 省略getter、setter及构造函数
}
public interface WifeRepository extends JpaRepository<Wife, Integer> {
}

为何Husband实体可以正确添加,但Wife实体却没有被级联添加呢?

Husband husband = new Husband(1, "Tim", new Wife(1, "Lucy"));
husbandRepository.save(husband);

Cascade用的均是Hibernate的类

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

---------------------------分割线-----------------------------

@Cascade({CascadeType.SAVE_UPDATE})
修改为
@Cascade({CascadeType.MERGE})
则级联新增、修改都可以实现,但是我想明确的指定为新增级联就是不行

开满天机
浏览 676回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java