Hibernate @OneToOne映射删除并重新插入会引发ConstraintViolationException

时间:2018-07-10 19:07:52

标签: hibernate one-to-one

我正在运行JUnit测试,该测试首先插入一个Drawing,然后删除该Drawing(首先插入和删除工作并达到预期的效果),然后将同一图形重新插入到表中并得到错误ConstraintViolationException。有关错误对话框以及我认为正在发生的事情,请参见下文。

绘画课(重要的东西)

@Entity
public class Drawing {
    private String userId;
    @Id
    private String featureId;
    private String type;
    @OneToOne(
            cascade = CascadeType.ALL
    )
    @JoinColumn(
            name = "fk_polygon_id"
    )
    private Polygon polygon;

要删除的回购代码并将图形插入到数据库中

public void removeDrawing(String id) {
    Drawing removeDrawing = findDrawingById(id);
    session.beginTransaction();
    session.delete(removeDrawing);
    session.flush();
    session.clear();
    session.getTransaction().commit();
}

public void addDrawing(Drawing drawing) {
    session.beginTransaction();
    session.saveOrUpdate(drawing);
    session.getTransaction().commit();
}

测试用例,

@Test
public void testAddDrawing() {
    logger.info("Testing adding drawing");
    drawingRepo.addDrawing(drawingList.get(0));
    Drawing drawing = drawingRepo.findDrawingById(drawingList.get(0).getFeatureId());
    Assert.assertNotNull(drawing);
    Assert.assertEquals(drawing.getFeatureId(), drawingList.get(0).getFeatureId());
}

@Test(dependsOnMethods = { "testAddDrawing" })
public void testRemoveDrawing() {
    logger.info("Testing removing drawing");
    drawingRepo.removeDrawing(drawingList.get(0).getFeatureId());
    Drawing drawing = drawingRepo.findDrawingById(drawingList.get(0).getFeatureId());
    Assert.assertNull(drawing);
    session.close();
}
@Test(dependsOnMethods = { "testRemoveDrawing" })
public void testAddNewDrawing() {
    logger.info("Testing adding drawing");
    drawingRepo.addDrawing(drawingList.get(0));
    Drawing drawing = drawingRepo.findDrawingById(drawingList.get(0).getFeatureId());
    Assert.assertNotNull(drawing);
    Assert.assertEquals(drawing.getFeatureId(), drawingList.get(0).getFeatureId());
}

问题是,当尝试重新插入图形时出现此错误

ERROR: insert or update on table "drawing" violates foreign key constraint "fkjo26qx3wf4sq8gv7e3hger1q1"
Detail: Key (fk_polygon_id)=(1) is not present in table "polygon".

所以我想这就是休眠状态试图将fk_polygon_id映射到第一个条目(id = 1),即使它已被删除。我试过冲洗并清除会话,但没有运气。有任何想法吗?

0 个答案:

没有答案