Hibernate更新一个到多个级联

时间:2016-02-06 13:18:01

标签: java hibernate postgresql sql-update one-to-many

我有两个实体,它们有一对多的关系。

Purchase ----------------< lineCommand

我已将这些实体映射到一起,并且一切正常,至少在我想保存或删除购买时,除非我执行更新,只有父级(购买将更新)且子级不会更新。

这里是Purchase和lineCommand的DDL: LineCommand:

CREATE TABLE purchaseproduct
(
  idpurchaseproduct serial NOT NULL,
  idpurchase integer,
  idproduct integer,
  qty double precision,
  price double precision,
  CONSTRAINT purchaseproduct_pkey PRIMARY KEY (idpurchaseproduct),
  CONSTRAINT purchaseproduct_idproduct_fkey FOREIGN KEY (idproduct)
      REFERENCES product (idproduct) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT purchaseproduct_idpurchase_fkey FOREIGN KEY (idpurchase)
      REFERENCES purchase (idpurchase) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

购买:

 CREATE TABLE purchase
    (
      idpurchase serial NOT NULL,
      code character varying(50),
      date timestamp without time zone,
      totalht double precision,
      tva double precision,
      totalttc double precision,
      CONSTRAINT purchase_pkey PRIMARY KEY (idpurchase)
    )

POJOS: LineCommand

 @Entity
    @Table(name = "purchaseProduct")
    @Access(AccessType.PROPERTY)
    public class LineCommand implements Serializable {


        private LongProperty idPurchaseProduct;
        private Product product;
        private Purchase purchase;
        private DoubleProperty sellPrice = new SimpleDoubleProperty();
        private DoubleProperty qty = new SimpleDoubleProperty();
        private DoubleProperty subTotal = new SimpleDoubleProperty();


        public LineCommand() {
            this.idPurchaseProduct = new SimpleLongProperty();
            this.product = new Product();
            this.purchase = new Purchase();

            this.sellPrice = new SimpleDoubleProperty();
            this.qty = new SimpleDoubleProperty();
            this.subTotal = new SimpleDoubleProperty();

            NumberBinding subTotalBinding = Bindings.multiply(this.qty, this.sellPrice);
            subTotal.bind(subTotalBinding);

        }

        @Id
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "purchase_seq_gen")
        @SequenceGenerator(name = "purchase_seq_gen", sequenceName = "purchaseproduct_idpurchaseproduct_seq", initialValue = 1, allocationSize = 1)
        @Column(name = "idpurchaseproduct ", unique = true, nullable = false)
        public long getIdPurchaseProduct() {
            return idPurchaseProduct.get();
        }

        public LongProperty idPurchaseProductProperty() {
            return idPurchaseProduct;
        }

        public void setIdPurchaseProduct(long idPurchaseProduct) {
            this.idPurchaseProduct.set(idPurchaseProduct);
        }

        @ManyToOne
        @JoinColumn(name = "idproduct")
        public Product getProduct() {
            return product;
        }

        public void setProduct(Product product) {
            this.product = product;
        }

        @ManyToOne
        @JoinColumn(name = "idpurchase")
        public Purchase getPurchase() {
            return purchase;
        }

        public void setPurchase(Purchase purchase) {
            this.purchase = purchase;
        }


        @Column(name = "price")
        public double getSellPrice() {
            return sellPrice.get();
        }

        public DoubleProperty sellPriceProperty() {
            return sellPrice;
        }

        public void setSellPrice(double sellPrice) {
            this.sellPrice.set(sellPrice);
        }

        @Column(name = "qty")
        public double getQty() {
            return qty.get();
        }

        public DoubleProperty qtyProperty() {
            return qty;
        }

        public void setQty(double qty) {
            this.qty.set(qty);
        }

        @Transient
        public double getSubTotal() {
            return subTotal.get();
        }

        public DoubleProperty subTotalProperty() {
            return subTotal;
        }

        public void setSubTotal(double subTotal) {
            this.subTotal.set(subTotal);
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            } else {
                Product product = ((LineCommand) obj).getProduct();
                Purchase purchase = ((LineCommand) obj).getPurchase();

                if (this.product.equals(product) && this.purchase.equals(purchase))
                    return true;
                else
                    return false;
            }
        }
    }

采购:

@Entity
@Table(name = "purchase")
@Access(AccessType.PROPERTY)
public class Purchase {
    private LongProperty idPurchase;
    private StringProperty codePurchase;
    private ObjectProperty<LocalDate> datePurchase;
    private DoubleProperty totalHt;
    private DoubleProperty tva;
    private DoubleProperty totalTTC;

    private Set<LineCommand> lineItems = new HashSet<LineCommand>(0);

    public Purchase() {
        this.idPurchase = new SimpleLongProperty();
        this.codePurchase = new SimpleStringProperty();
        this.datePurchase = new SimpleObjectProperty<>();
        this.totalHt = new SimpleDoubleProperty();
        this.tva = new SimpleDoubleProperty();
        this.totalTTC = new SimpleDoubleProperty();


    }

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "purchase_seq_gen")
    @SequenceGenerator(name = "purchase_seq_gen", sequenceName = "purchase_idpurchase_seq", initialValue = 1, allocationSize = 1)
    @Column(name = "idpurchase", unique = true, nullable = false)
    public long getIdPurchase() {
        return idPurchase.get();
    }

    public LongProperty idPurchaseProperty() {
        return idPurchase;
    }

    public void setIdPurchase(long idPurchase) {
        this.idPurchase.set(idPurchase);
    }

    @Column(name = "code")
    public String getCodePurchase() {
        return codePurchase.get();
    }

    public StringProperty codePurchaseProperty() {
        return codePurchase;
    }

    public void setCodePurchase(String codePurchase) {
        this.codePurchase.set(codePurchase);
    }

    @Column(name = "date")
    @Convert(converter = LocalDatePersistanceConverter.class)
    public LocalDate getDatePurchase() {
        return datePurchase.get();
    }

    public ObjectProperty<LocalDate> datePurchaseProperty() {
        return datePurchase;
    }

    public void setDatePurchase(LocalDate datePurchase) {
        this.datePurchase.set(datePurchase);
    }

    @Column(name = "totalHt")
    public double getTotalHt() {
        return totalHt.get();
    }

    public DoubleProperty totalHtProperty() {
        return totalHt;
    }

    public void setTotalHt(double totalHt) {
        this.totalHt.set(totalHt);
    }

    @Column(name = "tva")
    public double getTva() {
        return tva.get();
    }

    public DoubleProperty tvaProperty() {
        return tva;
    }

    public void setTva(double tva) {
        this.tva.set(tva);
    }

    @Column(name = "totalTTC")
    public double getTotalTTC() {
        return totalTTC.get();
    }

    public DoubleProperty totalTTCProperty() {
        return totalTTC;
    }

    public void setTotalTTC(double totalTTC) {
        this.totalTTC.set(totalTTC);
    }


    @OneToMany(mappedBy = "purchase", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    public Set<LineCommand> getLineItems() {
        return this.lineItems;
    }

    public void setLineItems(Set<LineCommand> lineItems) {
        this.lineItems = lineItems;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        } else {

            if (this.idPurchase.getValue() == ((Purchase) obj).getIdPurchase())
                return true;
            else
                return false;
        }
    }

}

她在那里我通过DAO进行了一些更新:

    Purchase
    public boolean update(Purchase obj) {
        try {
            if (!session.isOpen())
                session = DatabaseUtil.getSessionFactory().openSession();
            session.beginTransaction();

            Purchase purchase = session.get(Purchase.class, obj.getIdPurchase());
            purchase.setCodePurchase(obj.getCodePurchase());
            purchase.setDatePurchase(obj.getDatePurchase());
            purchase.setTotalHt(obj.getTotalHt());
            purchase.setTva(obj.getTva());
            purchase.setTotalTTC(obj.getTotalTTC());
            //purchase.getLineItems().clear();
            // Here where i set line items
            // purchase.setLineItems(obj.getLineItems());


            session.getTransaction().commit();
            session.close();
            return true;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

注意:只有父级才会更新,因此更新不会级联。

1 个答案:

答案 0 :(得分:0)

obj.getLineItems()返回一组分离的实例(它们与当前的Hibernate会话无关)。解决问题的最简单方法是在提交事务之前合并Purchase

purchase = session.merge(purchase);

这样,合并操作将级联到关联的LineCommand实例。