2

Consider two entities:

@Entity
public class A implements Serializable {
    ...

    @OneToMany(mappedBy = "a", orphanRemoval = true)
    @Cascade(CascadeType.ALL)
    @JsonManagedReference
    private List<B> bs = new ArrayList<B>();

    ...
}

@Entity
public class B implements Serializable {
    ...

    @ManyToOne
    @JsonBackReference
    private A a;
    ...
}

I'm receiving a JSON representation of A and loading it via a @RequestBody in one of my Spring controllers (in this case this is an existing entity that already has an identifier; the following issue does not apply to new entities).

As you might expect, calling session.saveOrUpdate does not auto-magically remove any B's (from the database) that were not in the deserialized A.bs collection. Additions to the collection do work, as do updates of individual entities in the collection.

What is the proper way to remove these objects? Does the request have to be structured differently for this to work? (Using Spring 3.1.1 / Hibernate 4.0.1)

jlb
  • 19,090
  • 8
  • 34
  • 65

1 Answers1

0

Edit:

Try adding CascadeType.DELETE_ORPHAN to the cascade annotation

@OneToMany(mappedBy = "a", orphanRemoval = true)
@Cascade(cascade = {CascadeType.ALL, CascadeType.DELETE_ORPHAN}, mappedBy = "a")
private List<B> bs = new ArrayList<B>();

source

Community
  • 1
  • 1
theon
  • 14,170
  • 5
  • 51
  • 74
  • My hibernate session does not have an instance of the entity in question attached to it.. are you saying I should explicitly try to attach it (ie. by fetching by id)? – jlb Jul 18 '12 at 08:46
  • No, I'm just suggesting to try calling merge() instead of saveOrUpdate(). – theon Jul 18 '12 at 12:53
  • Unfortunately a merge doesn't seem to do anything. My controller's method has the @Transactional annotation.. would this effect anything my chance? – jlb Jul 19 '12 at 15:13
  • I found an answer for a similar question (see updated answer). In that question they didn't specifically say that their entity was coming from a HTTP request body, but it sounds like a similar problem. Worth a try. – theon Jul 20 '12 at 09:08
  • Thanks, unfortunately that's using older Hibernate annotations. `CascadeType.DELETE_ORPHAN` has been deprecated and replaced by `orphanRemoval = true` on `@OneToMany` – jlb Jul 24 '12 at 08:37