简体   繁体   中英

Qualified OneToMany-ManyToOne relation

i try to build a sample qualified relation and get a null value for the qualifier column in the join table.

Error:

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

Entities:

@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");
        ...
    }

}

Insert invocation:

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();

    }

Anyone an idea what is wrong here?

Set both sides of your relationship and also remove the nullable=false constraint to see if the provider ends up setting the field. As JB Nizet pointed out, you are using a JoinColumn relationship instead of a relation table, which will force the "TIRE_POSITION" to be put in the Tire table; Some providers (EclipseLink) will insert the Tire table with all the data from the Tire entity and then later on update the reference with mapping data contained in other entities. Since the "TIRE_POSITION" field is mapped through Bike, it will get updated later. If so, you can either remove the database constraint or set your database to delay constraint processing until after the transaction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM