使用Hibernate我在更新其循环时遇到异常

时间:2013-10-29 09:57:11

标签: java hibernate struts-1

我正在使用hibernate。我将数据插入两个表并更新一个表。 更新时我收到异常 - 因为对象引用了未保存的瞬态实例 - save the transient instance before flushing: com.treamis.inventory.goodsReceived.GoodsRecieved.. 如果我删除更新相关代码,它的工作正常

try {
            SalesInventoryDAO dao = new SalesInventoryDAO();
            sess = HibernateUtil.getSessionFactory().openSession();
            Transaction tr = sess.beginTransaction();
            GoodsRecievedForm item = (GoodsRecievedForm) form;
            GoodsRecieved bk = new GoodsRecieved();
            bk.setGoodsId(item.getGoodsId());
            InventoryOrder order = (InventoryOrder) sess.get(InventoryOrder.class, item.getOrderNo());
            bk.setOrderNo(order);
//            if (order.getQuotation().getQuotationNo() != null) {
//                bk.setQuotation(order.getQuotation().getQuotationNo());
//            } else {
//                bk.setQuotation(null);
//            }

            java.util.Date temp = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(item.getRecievedDate());
            java.sql.Date temp1 = new java.sql.Date(temp.getTime());
            bk.setRecievedDate(temp1);
            bk.setOrderQty(order.getTotalqty());
            bk.setReceivedPersonName(item.getReceivedPersonName());
            bk.setReceivedQty(item.getReceivedQty());
            bk.setConditionOfMaterial(item.getConditionOfMaterial());
            UserEntity msg;
            HttpSession session = request.getSession(false);
            msg = (UserEntity) session.getAttribute("user");
            bk.setAddedBy(msg);
            bk.setAddedDate(new Date());
            int[] item1111 = item.getGoodsDetails();
            String[] productre = item.getGoodsDetailsName();
            float proqty[] = item.getGoodsDetailsQty();
            float price[] = item.getGoodsDetailsPrice();
            float receivedqty[] = item.getReceivedquantity();
            GoodsReceivedDetails mb;
            Set<GoodsReceivedDetails> purDetails = new HashSet<GoodsReceivedDetails>();
            for (int i = 0; i < productre.length; i++) {
                mb = new GoodsReceivedDetails();
                mb.setGoodsDetailsName(productre[i]);
                mb.setGoodsDetailsQty(proqty[i]);
                mb.setGoodsDetailsPrice(price[i]);
                mb.setReceivedquantity(receivedqty[i]);
                //System.out.println("productre" + productre[i]);
                int id3 = item1111[i];
                //System.out.println("id3id3id3id3" + id3);
                // int id3 = Integer.parseInt(productre[i]);
                Item idf = (Item) sess.get(Item.class, id3);
                System.out.println("mb.getReceivedquantity()" + mb.getReceivedquantity());
                float qty = (idf.getItemStock() + mb.getReceivedquantity());
                System.out.println("qtyqty" + qty);
                mb.setItemId(idf);
                Query qry = sess.createQuery("UPDATE Item set itemStock='" + qty + "' where itemId='" + idf.getItemId() + "'");
                qry.executeUpdate();
//                dao.updateitem(qty, idf,sess);
                //dao.updateitem(idf);
                mb.setGoodsId(bk);
                sess.save(mb);
                purDetails.add(mb);
            }
            bk.setGoodsDetails(purDetails);
            sess.save(bk);
            tr.commit();
            //System.out.println("comming");
//            List ls = gdao.getOrderItems(order.getOrderId());
//            for (Iterator it = ls.iterator(); it.hasNext();) {
//                InventoryOrderDetails inv = (InventoryOrderDetails) it.next();
//                gdao.updateitem(inv.getItemId().getItemStock() + bk.getReceivedQty(), inv.getItemId());
//            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sess.close();
        }

这是我的堆栈跟踪:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.treamis.inventory.goodsReceived.GoodsRecieved
    at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:219)
    at org.hibernate.type.EntityType.getIdentifier(EntityType.java:397)
    at org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:242)
    at org.hibernate.type.TypeFactory.findDirty(TypeFactory.java:597)
    at org.hibernate.persister.entity.AbstractEntityPersister.findDirty(AbstractEntityPersister.java:3123)
    at org.hibernate.event.def.DefaultFlushEntityEventListener.dirtyCheck(DefaultFlushEntityEventListener.java:479)
    at org.hibernate.event.def.DefaultFlushEntityEventListener.isUpdateNecessary(DefaultFlushEntityEventListener.java:204)
    at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:127)
    at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:196)
    at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:76)
    at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:35)
    at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:969)
    at org.hibernate.impl.SessionImpl.executeUpdate(SessionImpl.java:1136)
    at org.hibernate.impl.QueryImpl.executeUpdate(QueryImpl.java:94)
    at com.treamis.inventory.goodsReceived.AddGoodsRecievedAction.addGoodsReceived(AddGoodsRecievedAction.java:112)
    at com.treamis.inventory.goodsReceived.AddGoodsRecievedAction.execute(AddGoodsRecievedAction.java:54)
    at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
    at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
    at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
    at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
    at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:305)
    at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
    at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
    at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.treamis.academics.examlist.SessionFilterServelet.doFilter(SessionFilterServelet.java:190)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.displaytag.filter.ResponseOverrideFilter.doFilter(ResponseOverrideFilter.java:125)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

这是One Entity GoodsReceived:

@Entity
public class GoodsRecieved implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int goodsId;
    @OneToOne
    private InventoryOrder orderNo;
//    private String quotation;
    private float orderQty;
    private String receivedPersonName;
    private float receivedQty;
    private String conditionOfMaterial;
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date recievedDate;
    @OneToOne
    private UserEntity addedBy;
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date addedDate;
    @OneToOne
    private UserEntity modifiedBy;
    @Temporal(javax.persistence.TemporalType.TIMESTAMP)
    private Date modifiedDate;
      @OneToMany(targetEntity = GoodsReceivedDetails.class, fetch = FetchType.LAZY)
    @JoinColumn(name = "goodsDetails", referencedColumnName = "goodsId")
    @Cascade(CascadeType.ALL)
    private Set<GoodsReceivedDetails> goodsDetails;

    public int getGoodsId() {
        return goodsId;
    }

    public void setGoodsId(int goodsId) {
        this.goodsId = goodsId;
    }

    public InventoryOrder getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(InventoryOrder orderNo) {
        this.orderNo = orderNo;
    }

    public float getOrderQty() {
        return orderQty;
    }

    public void setOrderQty(float orderQty) {
        this.orderQty = orderQty;
    }

    public String getReceivedPersonName() {
        return receivedPersonName;
    }

    public void setReceivedPersonName(String receivedPersonName) {
        this.receivedPersonName = receivedPersonName;
    }

    public float getReceivedQty() {
        return receivedQty;
    }

    public void setReceivedQty(float receivedQty) {
        this.receivedQty = receivedQty;
    }

//    public String getQuotation() {
//        return quotation;
//    }
//
//    public void setQuotation(String quotation) {
//        this.quotation = quotation;
//    }

    public Date getRecievedDate() {
        return recievedDate;
    }

    public void setRecievedDate(Date recievedDate) {
        this.recievedDate = recievedDate;
    }

    public UserEntity getAddedBy() {
        return addedBy;
    }

    public void setAddedBy(UserEntity addedBy) {
        this.addedBy = addedBy;
    }

    public Date getAddedDate() {
        return addedDate;
    }

    public void setAddedDate(Date addedDate) {
        this.addedDate = addedDate;
    }

    public UserEntity getModifiedBy() {
        return modifiedBy;
    }

    public void setModifiedBy(UserEntity modifiedBy) {
        this.modifiedBy = modifiedBy;
    }

    public Date getModifiedDate() {
        return modifiedDate;
    }

    public void setModifiedDate(Date modifiedDate) {
        this.modifiedDate = modifiedDate;
    }

    public String getConditionOfMaterial() {
        return conditionOfMaterial;
    }

    public void setConditionOfMaterial(String conditionOfMaterial) {
        this.conditionOfMaterial = conditionOfMaterial;
    }

    public Set<GoodsReceivedDetails> getGoodsDetails() {
        return goodsDetails;
    }

    public void setGoodsDetails(Set<GoodsReceivedDetails> goodsDetails) {
        this.goodsDetails = goodsDetails;
    }   
}

这是我的另一个实体商品已收到的详细信息:

    @Entity
    public class GoodsReceivedDetails implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int goodsDetailsId;
    private String goodsDetailsName;
    private float goodsDetailsQty;
    private float goodsDetailsPrice;
    private float receivedquantity;
    @ManyToOne
    @JoinColumn(name = "goodsId")
    private GoodsRecieved goodsId;
    @OneToOne()
    private Item itemId;

    public int getGoodsDetailsId() {
        return goodsDetailsId;
    }

    public void setGoodsDetailsId(int goodsDetailsId) {
        this.goodsDetailsId = goodsDetailsId;
    }

    public String getGoodsDetailsName() {
        return goodsDetailsName;
    }

    public void setGoodsDetailsName(String goodsDetailsName) {
        this.goodsDetailsName = goodsDetailsName;
    }

    public float getGoodsDetailsQty() {
        return goodsDetailsQty;
    }

    public void setGoodsDetailsQty(float goodsDetailsQty) {
        this.goodsDetailsQty = goodsDetailsQty;
    }

    public float getGoodsDetailsPrice() {
        return goodsDetailsPrice;
    }

    public void setGoodsDetailsPrice(float goodsDetailsPrice) {
        this.goodsDetailsPrice = goodsDetailsPrice;
    }

    public GoodsRecieved getGoodsId() {
        return goodsId;
    }

    public void setGoodsId(GoodsRecieved goodsId) {
        this.goodsId = goodsId;
    }

    public Item getItemId() {
        return itemId;
    }

    public void setItemId(Item itemId) {
        this.itemId = itemId;
    }

    public float getReceivedquantity() {
        return receivedquantity;
    }

    public void setReceivedquantity(float receivedquantity) {
        this.receivedquantity = receivedquantity;
    }
}

3 个答案:

答案 0 :(得分:0)

我认为您的ORM定义错误,请尝试以下

你有这个

   @OneToMany(targetEntity = GoodsReceivedDetails.class, fetch = FetchType.LAZY)
   @JoinColumn(name = "goodsDetails", referencedColumnName = "goodsId")
   @Cascade(CascadeType.ALL)
   private Set<GoodsReceivedDetails> goodsDetails;

试试这个

   @OneToMany(mappedBy = "goodsId", targetEntity = GoodsReceivedDetails.class, fetch = FetchType.LAZY)
   private Set<GoodsReceivedDetails> goodsDetails;

当您将@JoinColumn放入GoodsRecieved课程时。你不应该把它用于双向关系。您应该使用mappedBy属性。

如果你想拥有双向关系GoodsRecievedGoodsReceivedDetails,那么作为GoodsReceivedDetails多边(目标)实体,他应该是关系定义OWNER,所以他应该定义@JoinColumn和非所有者方,即GoodsRecieved他应该使用mappedBy属性来说它是双向的而不是新的关系定义。

在您的情况下,您已定义Two Uni-directional mappings :(。可能这可能是问题。

希望它有所帮助。

答案 1 :(得分:0)

我认为你的问题在这里:

    ...
    mb.setGoodsId(bk);
    sess.save(mb);
    purDetails.add(mb);
}
bk.setGoodsDetails(purDetails);
sess.save(bk);
tr.commit();
...

在坚持mb之前,您正试图坚持bk。 首先尝试保留bk

答案 2 :(得分:0)

goodsIdGoodsReceivedDetails属性的注释下方说明,您有一列goodsId,它是引用GoodsRecieved的外键:

@ManyToOne
@JoinColumn(name = "goodsId")
private GoodsRecieved goodsId;

因此@JoinColumngoodsDetails GoodsRecieved不需要@OneToMany(mappedBy = "goodsId", fetch = FetchType.LAZY) @Cascade(CascadeType.ALL) private Set<GoodsReceivedDetails> goodsDetails; 。将映射更改为:

@Cascade(CascadeType.ALL)

这里GoodsReceivedDetails引入了传递持久性。有了这个,当您实例化一个新的GoodsRecieved并将其添加到GoodsReceivedDetails时,GoodsReceivedDetails应立即成为持久性。您不需要通过在Session界面上调用save()来显式地建立mb.setGoodsId(bk); sess.save(mb); purDetails.add(mb); } bk.setGoodsDetails(purDetails); sess.save(bk); 持久性。

所以你可以替换这段代码:

mb.setGoodsId(bk);
purDetails.add(mb);
}
bk.setGoodsDetails(purDetails);
sess.save(bk);

用这个:

GoodsReceivedDetails

如果GoodsReceivedDetails被持久性GoodsRecieved引用,则级联注释会告诉Hibernate使任何新的{{1}}实例持久化(即将其保存在数据库中)。