JPA插入失败,因为我的外键中的值为零

时间:2014-02-19 08:46:57

标签: java jpa orm entity-relationship

我有以下多重性: Order3d 1 ----- 1 .. * DrawFile 1 ----- 1 .. * Order3dLine

当我想保存Order3d对象时,我得到一个约束违规,因为DrawFile.id放在我的Order3dLine字段中,我的外键中有一个零值

Hibernate: insert into order3d (delivery, demand_date, estimate_date, order_date, person_id, state) values (?, ?, ?, ?, ?, ?) //OK
Hibernate: insert into draw (dimension, filename, format, hashname, hole, order3d_id, readable, size, slope, wall) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) //OK
Hibernate: insert into order3dline (duration, produced, quantity, color, draw_id, material) values (?, ?, ?, ?, ?, ?)
09:33:08,779 TRACE BasicBinder:84 - binding parameter [1] as [SMALLINT] - 0
09:33:08,780 TRACE BasicBinder:84 - binding parameter [2] as [SMALLINT] - 0
09:33:08,780 TRACE BasicBinder:84 - binding parameter [3] as [SMALLINT] - 2
09:33:08,781 TRACE BasicBinder:84 - binding parameter [4] as [INTEGER] - 0
09:33:08,781 TRACE BasicBinder:84 - binding parameter [5] as [INTEGER] - 0 //NOT OK
09:33:08,782 TRACE BasicBinder:84 - binding parameter [6] as [VARCHAR] - Something

我的java类是这样的(我没有把所有属性和方法都放在一起,因为我猜它不相关):

@Entity
@Table (name="draw")
public class DrawFile implements Serializable {
    @OneToMany(mappedBy="draw", fetch = FetchType.EAGER, cascade=CascadeType.ALL)
    private Set<Order3dLine> line3ds=new HashSet<Order3dLine>(3);
}

@Entity
@Table (name="order3dline")
public class Order3dLine implements Serializable {
    private static final long serialVersionUID = 3993578603382571145L;

    @EmbeddedId
    private Order3dLine3dPK id=new Order3dLine3dPK();
    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name = "draw_id", referencedColumnName="id", insertable = false, updatable = false)
    private DrawFile draw;
}

@Embeddable
public class Order3dLine3dPK implements Serializable {
    @Column(name="draw_id", columnDefinition="id", insertable=false, updatable=false)
    private int drawId;
    private String material="";
    private int color;
}

是否缺少注释?

1 个答案:

答案 0 :(得分:0)

此错误的一个常见错误是您持久保存order3d对象,但将非托管order3d对象设置为order3dLine对象的引用,并且由于引用的order3d对象未持久化,order3dLine对象获得{{1 key - 尝试持久化order3d对象并使用托管order3d对象重新设置order3dLine对象的引用,然后持久化order3dLine对象,使order3dLine对象获得对JPA实体的引用,而不仅仅是POJO。