我想使用JPArepository“保存”(如添加功能)更新表中的数据。添加它的工作,但更新不一样。
错误
java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`timesheetdb`.`app`, CONSTRAINT `app_ibfk_1` FOREIGN KEY (`batch_id`) REFERENCES `batch` (`batch_id`))
这是我的代码
App.java
@Entity
@Table(name = "app")
public class App {
@Id
@GeneratedValue
@Column(name="app_id" , nullable = true)
private int app_id;
@Column(name="app_no")
private String app_no;
@ManyToOne(fetch = FetchType.LAZY ,cascade = {CascadeType.PERSIST,CascadeType.MERGE} )
@JoinColumn(name="batch_id" , referencedColumnName = "batch_id",insertable=false, updatable=false)
private Batch batch = new Batch() ;
//get and set
Batch.java
@Entity
@Table(name = "batch")
public class Batch {
@Id
@GeneratedValue
@Column(name="batch_id" , unique = true, nullable = false ,insertable= false , updatable = false)
private int batch_id;
@Column(name="batch_name")
private String batch_name;
//get and set
休眠日志
Hibernate: insert into batch (batch_name, batch_id) values (?, ?)
Hibernate: insert into app (app_id,app_no, batch_id) values (?, ?,?)
问题
1。为什么不更新日志?
2。有时我测试是否看到错误,我看到了新的约束,例如FKsbmff76rtfh40rncf2110t4pf而不是app_id约束?
3。问题是因为我将多对一映射错了吗?
答案 0 :(得分:0)
而不是
cascade = {CascadeType.PERSIST,CascadeType.MERGE}
尝试使用,
cascade = CascadeType.ALL
您可以参考链接https://vladmihalcea.com/a-beginners-guide-to-jpa-and-hibernate-cascade-types/以获得更好的理解。
还从下面一行中删除新的Batch()
@ManyToOne(fetch = FetchType.LAZY ,cascade = {CascadeType.PERSIST,CascadeType.MERGE} )
@JoinColumn(name="batch_id" , referencedColumnName = "batch_id",insertable=false, updatable=false)
private Batch batch = new Batch() ;