我有两个实体
实体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不太熟悉所以如果您需要澄清我的问题或者您是否需要更多信息,请告诉我。
答案 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
//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);
}