简体   繁体   中英

Hibernate updating one to many collection when object removed from collection

I have run into a nasty bug with jpa and hibernate. I have a billing class with the following annotation:

@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="ch1_id", referencedColumnName="id")
private List<BillingItem>billingItems = new ArrayList<BillingItem>();

Now I need to filter deleted items from the collection but cannot use anything but jpa. No hibernate specific annotations allowed. So I wrote a post load function:

@PostLoad
public void postLoad() {
    ArrayList<BillingItem>tempItems = new ArrayList<BillingItem>();

    Iterator<BillingItem> i = this.billingItems.iterator();
    BillingItem item;
    while(i.hasNext()) {
        item = i.next();            
        if( item.getStatus().equals("D")) {
            tempItems.add(item);                
        }                       
    }

    this.billingItems.removeAll(tempItems);
}

However when there are deleted items to filter I'm seeing

Hibernate: update billing_on_item set ch1_id=null where ch1_id=? and id=?

which produces an exception because ch1_id is a foreign key and cannot be null. However hibernate is binding the parameters to correct values. Why is this update occurring in the first place? How do I correct the error?

Thanks in advance,

Randy

By removing the items from the collection, you're telling Hibernate that the association between the two entities doesn't exist anymore, so obviously, Hibernate removes what materializes this association in the database: it sets the foreign key to null.

What you probably want is just a getter in your entity that returns only the non-deleted items:

public List<BillingItem> getNonDeletedItems() {
    List<BillingItem> result = new ArrayList<BillingItem>();
    for (BillingItem item : this.billingItems) {
        if (!"D".equals(item.getStatus()) {
            result.add(item);
        }
    }
    return result;
}

The @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) line says that it will cascade ALL updates. Look into CascadeType .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM