我有这种关系
@OneToOne(orphanRemoval = true, optional = true, cascade = {CascadeType.ALL}, mappedBy = "publicProcurement", fetch = FetchType.LAZY)
@Getter
@Setter
private Announcement announcement;
@OneToOne
@JoinColumn(name = "public_procurement_id", nullable = false, insertable = false, updatable = false)
@Getter
@Setter
private PublicProcurement publicProcurement;
这里是我的外键约束
<addForeignKeyConstraint baseColumnNames="public_procurement_id" baseTableName="announcement" constraintName="announcement_public_procurement_ibfk_1" onDelete="RESTRICT" onUpdate="RESTRICT" referencedColumnNames="id" referencedTableName="public_procurement"/>
现在在我的服务中我这样做
@Override
public void addAnnouncement(final Integer id, final PublicProcurement publicProcurementForm) {
PublicProcurement publicProcurement = get(id);
Announcement announcement = publicProcurementForm.getAnnouncement();
announcement.setApprovedName(userService.getUserName());
announcement.setPublicProcurement(publicProcurement);
announcementService.save(announcement);
publicProcurement.setAnnouncement(announcement);
save(publicProcurement);
}
但是当我保存announcementService.save(公告);我收到以下异常
Caused by: java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`etendering_test`.`announcement`, CONSTRAINT `announcement_public_procurement_ibfk_1` FOREIGN KEY (`public_procurement_id`) REFERENCES `public_procurement` (`id`))
at org.mariadb.jdbc.internal.SQLExceptionMapper.get(SQLExceptionMapper.java:132) ~[mariadb-java-client-1.1.2.jar:na]
at org.mariadb.jdbc.internal.SQLExceptionMapper.throwException(SQLExceptionMapper.java:106) ~[mariadb-java-client-1.1.2.jar:na]
at org.mariadb.jdbc.MySQLStatement.executeQueryEpilog(MySQLStatement.java:266) ~[mariadb-java-client-1.1.2.jar:na]
at org.mariadb.jdbc.MySQLStatement.execute(MySQLStatement.java:289) ~[mariadb-java-client-1.1.2.jar:na]
at org.mariadb.jdbc.MySQLStatement.executeUpdate(MySQLStatement.java:317) ~[mariadb-java-client-1.1.2.jar:na]
at org.mariadb.jdbc.MySQLPreparedStatement.executeUpdate(MySQLPreparedStatement.java:150) ~[mariadb-java-client-1.1.2.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133) ~[hibernate-core-4.2.7.Final.jar:4.2.7.Final]
我尝试了一切,但我不知道Hibernate的错误。任何想法的人?
问候。
答案 0 :(得分:0)
我认为在这种情况下你确实错误了插入优先级,所以在保存“announcement”对象之前你必须保证带有约束ID的publicProcerument已经存在于DB上:
也许你应该尝试在下面重新订购:
announcementService.save(announcement);
publicProcurement.setAnnouncement(announcement);
save(publicProcurement);
要:
publicProcurement.setAnnouncement(announcement);
save(publicProcurement);
announcementService.save(announcement);
删除注释insertable = false,updatable = false
如果这无法帮助您解决问题,那么最好向我展示您的实体。