我对Java和JPA /休眠非常陌生。 对于上述表结构,我创建了以下实体。
表1:
@Entity
public class Table1 implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="work_item_no")
private String workItemNo;
@OneToMany(mappedBy="tcTcr", cascade = CascadeType.ALL)
private List<Table2> table2;
表2:
@Entity
@Table(name="Table2")
public class Table2 implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="errtrack_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long errtrackId;
@ManyToOne
@JoinColumn(name="work_item_no")
private Table1 table1;
@OneToOne(fetch = FetchType.LAZY, mappedBy="table2", cascade = CascadeType.ALL)
private Table3 table3;
@OneToMany(mappedBy="table2", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Table4> table4s = new ArrayList<Table4>();
表3:
@Entity
public class Table3 implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="errtrack_id")
private long errtrackId;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name="errtrack_id")
@MapsId
private Table2 table2;
表4:
@Entity
@IdClass( Table4PK.class )
public class Table4 implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="errtrack_id")
private long errtrackId;
@Id
@Column(name="line_item_no")
private int lineItemNo;
@ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@JoinColumn(name="errtrack_id",referencedColumnName ="errtrack_id")
@MapsId
private Table2 table2;
Table4PK:
public class Table4PK implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name="errtrack_id")
private long errtrackId;
@Column(name="line_item_no")
private int lineItemNo;
我使用JpaRepository.save保存Table1。
Table1 table1 = trans.GetTable1();
List<Table2> tb2Arr = new ArrayList<Table2>();
for (Task task : request.getTasks()) {
Table2 table2 = trans.GetTable2(task);
table2.setTable1(table1);
Table3 table3 = trans.GetTable3());
table2.setTable3(table3);
table3.setTable2(table2);
int index = 0;
for (Trade trade : table2.getTable4s()) {
index++;
Table4 table4 = trans.GetTable4(trade, index);
table4.setTable2(table2);
table2.getTable4s().add(table4);
}
tb2Arr.add(table2);
}
table1.setTable2s(tb2Arr); 表1已保存表1 = table1Repo.save(table1);
在Table3之前,我一切正常。但是由于未填充自动生成的值,因此未保存Table4。
Table4具有复合键,而compiste键中的一个字段是另一张表中的foriegn_key。
错误:
o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 547, SQLState: 23000
2018-06-27 02:01:15.453 ERROR 15512 --- [nio-8090-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : The INSERT statement conflicted with the FOREIGN KEY constraint...
在事件探查器中,我看到从Table2生成的errtrack_id
未填充在Table4上。
任何帮助将不胜感激。 -谢谢。