abdou amer February 2016

Hibernate many to many: A collection with cascade all-delete-orphan

I have two entities, Purchase and Product. They have many to many relationship:

Purchase >-------purchaseProduct---------< Product

beteween them I have mapped those entities together. Everything works fine while saving or deleting a Purchase. Exceptes when I perform an update, only the parent (purchase will be update) and children (LineCommand) won't be updated(Means delete old children from database and insert the new ones).

Here the DDL for both Purchase and Product and Association: LineCommand:

Purchase:

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

Product:

CREATE TABLE product (
  idProduct      serial primary key,
  nameAr         varchar(50),
  nameFr         varchar(50),
  preference       varchar(50),
  qtyStart       double PRECISION,
  qtyInHand      double PRECISION,
  sellPrice      double PRECISION ,
  purchasePrice  double PRECISION,
  taxe           double PRECISION
);

LineCommand:

CREATE TABLE purchaseProduct (
      idPurchase integer,
      idProduct integer,
      qty double PRECISION, 
      price double  PRECISION,
      primary key(idPurchase,idProduct),
      foreign key(idPurchase) references purchase(idPurchase),
      foreign key(idProduct) references product(idProduct) 
    );

The mapping for above entities:

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

Answers


Dragan Bozanovic February 2016

You are setting a new lineItems collection instance on the Purchase.

Replace:

purchase.setLineItems(obj.getLineItems())

with:

purchase.getLineItems().addAll(obj.getLineItems())

Post Status

Asked in February 2016
Viewed 2,612 times
Voted 12
Answered 1 times

Search




Leave an answer