Mark Estrada
Mark Estrada

Reputation: 9191

Not Null Property Exception with JPA onetoone mapping

I am trying my way around JPA but I cant get this to work the way I understand them.

Its the onetoone bidirectional mapping between an Order and an OrderInvoice class which is a required association

My entities are marked as this

@Entity
@Table(name = "Orders")
public class Order {
    @Id
    @GeneratedValue
    @Column(name = "ORDER_ID")
    private int orderId;

    @OneToOne(optional=false,cascade=CascadeType.ALL, mappedBy="order", targetEntity=OrderInvoice.class)
    private OrderInvoice invoice;
}

@Entity
@Table(name = "ORDER_INVOICE")
public class OrderInvoice {
    @Id
    @GeneratedValue
    @Column(name = "INVOICE_ID", nullable = false)
    private int invoiceId;

    @OneToOne(optional = false)
    @JoinColumn(name="ORDER_ID")
    private Order order;
}

My test class is like this.

@Test
public void createOrder() {
    Order order = createOrderImpl();
    assertNotNull(order);
}

private Order createOrderImpl() {
    OrderInvoice orderInvoice = new OrderInvoice(new Date(), 100.0, null,
            null, new Date());
    Order order = new Order(100.0, "JOHN Doe's Order", new Date(), new Date(),orderInvoice);
    orderDao.create(order);
    return order;
}

But I am encountering below problem when I run my Test

javax.persistence.PersistenceException: org.hibernate.PropertyValueException: not-null property references a null or transient value: order.OrderInvoice.order
    at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:614)

Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value: order.OrderInvoice.order
    at org.hibernate.engine.Nullability.checkNullability(Nullability.java:95)

Upvotes: 2

Views: 1279

Answers (1)

Andrey
Andrey

Reputation: 696

try to

orderInvoice.setOrder(order);
orderDao.create(order);

Upvotes: 1

Related Questions