dimanche 15 mars 2015

Error when trying to save entities with mapping in Spring-JPA

I have the following entity relationship:



@Entity
@Table(name="order_info")
public class OrderInfo{
@OneToMany(mappedBy="orderInfo",fetch=FetchType.EAGER,cascade=CascadeType.ALL)
@JsonIgnore
private List<OrderItem> orderItems;
}


@Entity
@Table(name="reason_codes")
public class ReasonCode{
//bi-directional many-to-one association to OrderItem
@JsonIgnore
@OneToMany(mappedBy="reasonCode",fetch=FetchType.EAGER,cascade=CascadeType.ALL)
private List<OrderItem> orderItems;
}


@Entity
@Table(name="order_item")
public class OrderItem{
//bi-directional many-to-one association to OrderInfo
@ManyToOne
@JoinColumn(name="order_info_id", nullable=false)
private OrderInfo orderInfo;

//bi-directional many-to-one association to ReasonCode
@ManyToOne
@JoinColumn(name="reason_code_id", nullable=false)
private ReasonCode reasonCode;
}


Each OrderInfo has many OrderItem, each ReasonCode can be mapped to multiple OrderItems, and each OrderItem MUST have 1 OrderInfo, and 1 ReasonCode.


And finally, the class to set everything up:



class setup{

...
List<OrderItem> orderItems = new ArrayList<OrderItem>();


for(...){
OrderItem item = new OrderItem();
ReasonCode rrCode = rcRepostory.findOne("2");
item.setReasonCode(rrCode);
orderItems.add(item);
}


OrderInfo orderInfo = new OrderInfo();
orderInfo.setOrderItems(orderItems);
orderInfoRepo.save(orderInfo);
}


Now, when I try to save the orderInfo entity, I get the following error:



Not-null property references a transient value - transient instance must be saved before current operation : model.OrderItem.reasonCode -> model.ReasonCode


Basically, what I wan to do is, when I save OrderInfo, I want the OrderItems to be saved as well.


From the many posts that I saw online, adding the fetch as eager, and cascade on the many-to-one mapping should resolve this. However, I still face the issue even after adding them.


The ReasonCode already exists in the database. What is the problem here?


Thanks.


Aucun commentaire:

Enregistrer un commentaire