How to persist arraylist objects via em.persist()?

1.6k views Asked by At

I'm making a shopping web application. In this application I need to proceed a order. In my case I created a method named create(Order o). When I'm adding a order to the database, I need to adding data to the OrderDetail table also. I tried with this,

public void create(Orders orders) throws RollbackFailureException, Exception {
    EntityManager em = null;
    try {
        utx.begin();
        em = getEntityManager();
        List<OrderDetail> orderDetail = orders.getOrderDetails();
        for (OrderDetail orderDetail1 : orderDetail) {
            em.persist(orderDetail1);
        }
        em.persist(orders);
        utx.commit();
    } catch (Exception ex) {
        ex.printSatckTrace();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

Setting data to OrderDetail object as,

List<OrderDetail> detailList = new ArrayList<OrderDetail>();
OrderDetail od = new OrderDetail();
od.setItem(item);
od.setPrice(item.getSalesPrice() + item.getShippingCost());
od.setQty(inputQty);
detailList.add(od);
o.setAmount(inputQty * (item.getSalesPrice() + item.getShippingCost()));
o.setOrderDate(String.valueOf(new SimpleDateFormat("dd-MM-yyyy").format(new Date())));
o.setOrderDetails(detailList);
Status status = new Status();
status.setStatusDesc("Pending");
o.setStatus(status);
orderJpa.create(o);

My entites,

Order

@Entity
public class Orders implements Serializable {
   private static final long serialVersionUID = 1L;
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;
   private String orderDate;
   private double amount;
   @OneToOne(cascade = CascadeType.ALL)
   private Status status;
   @OneToMany(mappedBy = "orders", cascade = CascadeType.ALL)
   private List<OrderDetail> orderDetails;
   @OneToOne(cascade = CascadeType.ALL)
   private Customer customer;

}

OrderDetail

@Entity
public class OrderDetail implements Serializable {

   private static final long serialVersionUID = 1L;
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;
   private double price;
   private double discount;
   private int qty;
   @ManyToOne(cascade = CascadeType.ALL)
   private Item item;
   @ManyToOne(cascade = CascadeType.ALL)
   private Orders orders;

}

Item

@Entity
public class Item implements Serializable {

   @OneToOne(mappedBy = "item", cascade = CascadeType.REMOVE)
   private ShoppingCart shoppingCart;
   private static final long serialVersionUID = 1L;
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;
   private String itemName;
   private double purchasedPrice;
   private String description;
   private int qty;
   private double salesPrice;
   private String itemCondition;
   private byte[] image;
   @OneToMany(mappedBy = "item", cascade = CascadeType.ALL)
   List<Offer> listOffers;
   @OneToMany(mappedBy = "item", cascade = CascadeType.ALL)
   List<WishList> listWishes;
   @ManyToOne(cascade = CascadeType.MERGE)
   Brand brand;
   @ManyToOne(cascade = CascadeType.MERGE)
   Category category;
   @ManyToOne(cascade = CascadeType.ALL)
   private Rating rating;
   @OneToMany(mappedBy = "item", cascade = CascadeType.ALL)
   private List<OrderDetail> orderDetails;
   private double shippingCost;    

}                                                                               

But I got the following error, How to fix this?

Exception Description: Cannot persist detached object [com.shopping.model.Item[ id=13 ]]. 
Class> com.shopping.model.Item Primary Key> [13]at    oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.persist(EntityManagerImpl.java:208)
at com.shopping.model.controllers.OrdersJpaController.create(OrdersJpaController.java:45)
at com.shopping.op.order.OrderAdd.execute(OrderAdd.java:133)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:619)
   Caused by: Exception [TOPLINK-7231] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs         (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
   Exception Description: Cannot persist detached object [com.shopping.model.Item[ id=13 ]]. 
   Class> com.shopping.model.Item Primary Key> [13]
2

There are 2 answers

1
vels4j On

If you are mapped OrderDetails with Order properly, the following code is enough to persist your order with order items.

    EntityManager em = getEntityManager();
    em.getTransaction().begin();
    em.persist(orders);
    em.getTransaction().commit();

A Sample entity class

@Entity
@Table(name = "ORDER")  
public class Order { 
 @OneToMany(cascade = CascadeType.ALL, 
             targetEntity = OrderItem.class, mappedBy = "orderId")
 private List<OrderItem> orderItems;
   // getter & setter
 }
0
begginerAll On

I changed persist(orders) to merge(orders). Now it works.

public void create(Orders orders) throws RollbackFailureException, Exception {
   EntityManager em = null;
    try {
        utx.begin();
        em = getEntityManager();        
        em.merge(orders);
        utx.commit();
    } catch (Exception ex) {
        ex.printSatckTrace();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}