0

I'm stuck with one example from "Java Persistence with Hibernate" book, chapter 7.1.3.

I modified example a little, because it was too simple.

I mapped two entities as one-to-one association with join table. It's bidirectional and optional:

@Entity
public class Shipment {


    @OneToOne(optional=true)
    @JoinTable(
        name="ITEM_SHIPMENT",
        joinColumns = @JoinColumn(name="SHIPMENT_ID"),
        inverseJoinColumns = @JoinColumn(name="AUCTION_ID")
    )
    private Item auction;

    ...


@Entity
public class Item {

    @OneToOne(mappedBy="auction", optional=true)
    @JoinTable(
        name="ITEM_SHIPMENT",
        joinColumns = @JoinColumn(name="AUCTION_ID"),
        inverseJoinColumns = @JoinColumn(name="SHIPMENT_ID")
    )
    private Shipment shipment;

    ...

But entity manager acts like association (on Item side) is not optional (Shiment side is OK). I'm expecting that entity manager will persist just one instance of Item without corresponding Shipment specified.

    Item newItem = new Item("item1");
    Shipment newShipment = new Shipment();
    newShipment.setState(ShipmentState.Start);

    em.persist(newItem);//line29      // save either of two objects (without links - newItem.getShipment() returns null)
    newShipment.setAuction(newItem);   // link them to each other
    newItem.setShipment(newShipment);
    em.persist(newShipment);//line32   // save second object

    Item newItemSecond = new Item("item2");
    em.persist(newItemSecond);//line35

Running this test code gives this exception on line 29 (with code em.persist(newItem);):

org.hibernate.PropertyValueException: not-null property references a null or transient value : com.example._7._1._3.simple.ann.Item.shipment

If I swap lines 29 and 32, it works, but mentioned exception gets thrown on line 35, it can't persist newItemSecond.

Is it a bug or am I misunderstanding something?

(My english is not very well, I'll appreciate if someone have corrected my text, but you don't have to).

  • Not sure that it works but try doing it by setting the id of the related table as null. !! and remove the `optional=true` also. – Dileep Oct 21 '14 at 11:06
  • @Dileep I don't understand, how to set "the id of the related table as null" and why to remove `optional=true` (I want the association to be optional)? – Mick Kropen Oct 21 '14 at 23:16
  • as far as i know, the child tables `id` is set as `null` for ignoring the updations on the child table. may be other options are also available but i haven't tried that. better check and replay me back. – Dileep Oct 24 '14 at 06:06

0 Answers0