Spring JPA使用@JoinColumn保存实体

时间:2016-01-12 17:48:02

标签: java spring jpa spring-data-jpa

我有两个实体

实体1

    @Entity
    @Table(name = "Table1")
    public class Table1{
    @Id
    @SequenceGenerator(name = "Table1_SEQ", sequenceName = "Table1_SEQ", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Table1_SEQ")
    @Column(name = "seq", updatable = false, unique = true, insertable = true)
    private Long seq;
    @Column(name = "number", updatable = false, insertable = true)
    private Long number;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "enumber", updatable = false, insertable = true)
    private Table2 table2;

实体2

    @Entity
    @Table(name = "Table2")
    public class Table2 {
    @Id
    @SequenceGenerator(name = "Table2_SEQ", sequenceName = "Table2_SEQ", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Table2_SEQ")
    @Column(name = "enumber")
    private Long eNumber;

我有一个扩展 JpaRepository

的存储库
public interface Table1Repository extends JpaRepository<Table1, Long> {

}

当我尝试使用

保存时
Table1Repository rep;
Table1 table1; // Assume this is initialized correctly
rep.save(table1);

我收到Foriegn Key约束错误 org.springframework.dao.DataIntegrityViolationException

Table1在列 enumber 上与Table2有外键关联,但我不想在Table2中插入任何内容。

如何保存到Table1?

我对Jpa不太熟悉所以如果您需要澄清我的问题或者您是否需要更多信息,请告诉我。

1 个答案:

答案 0 :(得分:0)

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "enumber", updatable = false, insertable = true)
    private Table2 table2; // THIS IS WRONG!

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "enumber", updatable = false, insertable = true)
    private Long enumberFKTable2; // THIS IS CORRECT!

   //getters and setters

使用所有弹簧注释实现另一个类似于table1的java类,名为table2。然后执行以下代码:

//First, make sure that the foreign key exists!
number enumber = entityManager.getReference(Enumber.class, enumberId);

//test

if(enumber != null){
Table 1 table1 = new Table1();
table1.setEnumber(enumber);
entityManager.persist(table1);
}