合格的OneToMany-ManyToOne关系

时间:2014-07-25 16:02:35

标签: java java-ee jpa persistence

我尝试构建一个样本限定关系,并为连接表中的限定符列获取一个空值。

错误:

Internal Exception: java.sql.SQLIntegrityConstraintViolationException: 
cannot insert NULL into 'TIRE_POSITION'

实体:

@Entity
public class Bike {

    @OneToMany(mappedBy = "bike", cascade=CascadeType.ALL)
    @MapKeyColumn(name="TIRE_POSITION", nullable=false)
    private Map<String, Tire> tires;

    ...
}


@Entity
public class Tire {

    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="BIKE_ID")
    private Bike bike;

    public enum TirePosition{
        FRONT("FRONT"), BACK("BACK");
        ...
    }

}

插入调用:

public void testIt(){
        Bike bike = new Bike();

        Tire tireFront = new Tire();
        Tire tireBack = new Tire();
        Map<String, Tire> tires = new HashMap<String, Tire>();
        tires.put(Tire.TirePosition.BACK.getPosition(), tireBack);
        tires.put(Tire.TirePosition.FRONT.getPosition(), tireFront);
        bike.setTires(tires);

        EntityTransaction trans = em.getTransaction();
        trans.begin();
        em.persist(bike);
        trans.commit();

    }

任何人都知道这里有什么问题?

1 个答案:

答案 0 :(得分:0)

设置关系的两边并删除nullable = false约束以查看提供程序是否最终设置字段。正如JB Nizet所指出的那样,你使用的是JoinColumn关系而不是关系表,这将强制关注表&#34; TIRE_POSITION&#34;放在轮胎表中;某些提供程序(EclipseLink)将使用来自Tire实体的所有数据插入Tire表,然后使用其他实体中包含的映射数据更新引用。自&#34; TIRE_POSITION&#34;字段通过Bike映射,稍后会更新。如果是这样,您可以删除数据库约束或将数据库设置为延迟约束处理直到事务之后。