I mapped two entities as one-to-one association with join table. It's bidirectional and optional:
Code:
@Entity
public class Shipment {
@OneToOne(optional=true)
@JoinTable(
name="ITEM_SHIPMENT",
joinColumns = @JoinColumn(name="SHIPMENT_ID"),
inverseJoinColumns = @JoinColumn(name="AUCTION_ID")
)
private Item auction;
...
}
Code:
@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.
Code:
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
Quote:
em.persist(newItem)
):
Quote:
org.hibernate.PropertyValueException: not-null property references a null or transient value : com.example.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).