如何通过em.persist()持久化arraylist对象?

时间:2013-12-14 17:00:35

标签: java persistence persist

我正在制作购物网络应用程序。在这个应用程序中,我需要进行订单。在我的例子中,我创建了一个名为create(Order o)的方法。当我向数据库添加订单时,我还需要将数据添加到OrderDetail表中。我试过这个,

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();
        }
    }
}

将数据设置为OrderDetail对象,

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);

我的好意,

顺序

@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;

}

项目

@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;    

}                                                                               

但我收到以下错误,如何解决此问题?

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 个答案:

答案 0 :(得分:0)

如果您正确地将OrderDetails与Order映射,则以下代码足以使您的订单与订单商品保持一致。

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

Sample实体类

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

答案 1 :(得分:0)

我改变了持久性(订单)以合并(订单)。现在它有效。

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();
        }
    }
}