26

I have a @OneToMany collection (list) that I would like to clear, and add new elements to in the same transaction.

Using

collection.clear();
collection.add(new EntityB());

Simply adds the new instance, and never removes anything. I have orphanRemoval = true for the collection field.

ADDED:

// Parent entity
@OneToMany(mappedBy = "product", orphanRemoval = true)
private List<Feature> features = new ArrayList<>();

// Child entity
@ManyToOne(cascade = CascadeType.ALL)
private Product product;

// Clear and add attempt
product.getFeatures().clear();

Feature feature = new Feature(product, ls);
product.getFeatures().add(feature);
4
  • Could you please post the Entity objects here. I'm suspecting 'updatable' and 'deletable' properties on the @ onetomany mapping
    – Zeus
    Jul 14, 2014 at 18:16
  • I wrote an example for you to test the problem. Please try it and confirm that my example still reproduces your problem.
    – V G
    Aug 11, 2014 at 10:21
  • I have tested my code without setting feature.setProduct(null) simply clearing the collection (as you did), but with (at least) the CascadeType.PERSIST in the Product entity and that works without problems.
    – V G
    Aug 13, 2014 at 10:13
  • I tested the same code with a different result. I wonder what the cause is... Aug 14, 2014 at 11:51

5 Answers 5

43
+50

You try to clear only one side of the bidirectional association.

So instead of:

collection.clear();

Try clearing both sides and it should work:

for(Iterator<Feature> featureIterator = features.iterator(); 
    featureIterator.hasNext(); ) {
    Feature feature = featureIterator .next();
    feature.setProduct(null);
    featureIterator.remove();
}

Also, remove the cascade from @ManyToOne and move it to @OneToMany.

Mind the unique constraints

However, if you have a unique constraint, this clear + add Anti-Pattern will not work since the INSERT action is executed before the DELETE one.

The proper way to do it is to check which entries need to be removed and just remove those. Then, add the new ones, and update the ones that got modified. This is how you do a collection merge properly.

4
  • 2
    I tried that. Still a new set of Feature instances are added to the database. I am surprised that it is so difficult to make this work... Aug 12, 2014 at 6:16
  • 2
    Cascade should be set on OneToMany, mot on the ManyToOne side. Move it and see if you still have this issue. Aug 12, 2014 at 6:25
  • Moving the cascade seemed to help. I would have sworn that I have tried all possible combinations of cascading (on either annotation too). Aug 13, 2014 at 7:47
  • I awared the bouty, although your specific suggestion did not entirely fix the problem. But it did bring me along. Aug 14, 2014 at 9:37
3

Turns out that the actual solution was using a @JoinColumn annotation instead of the mappedBy="" parameter.

4
  • 4
    You are free to accept any solutions you want, but you probably do not understand what mappedBy does and what the implications COULD be...
    – V G
    Aug 13, 2014 at 15:53
  • I think I do understand what mappedBy does. But if you see any problems with my soltion, you are more than welcome to enlighten me. At least I can say that I could not make cascaded delete (from parent to children) work when the relation was "mappedBy" the child's parent property. Aug 14, 2014 at 9:39
  • there should be one accepted answer and one accepted by the comumunity answer Jan 12, 2017 at 17:00
  • Thanks for your answer. I have the same problem and this bug is still in Hibernate. We manually call entityManager.flush() after clearing the collection before adding new entities to get around this bug.
    – sloth
    Sep 13, 2017 at 9:27
3

This really seems to be a bug in many versions of Hibernate. I have tested it with EclipseLink and it works there without problem.

As workaround in Hibernate (tested in Hibernate 4.3.6-Final): Remove any cascading in the Feature entity and add CascadeType.PERSIST (or CascadeType.ALL) in the Product entity.

Just to make sure that it does not work, try the following:

EntityManager em = ...//fetch the entitymanager. If a Container-managed transaction, you already got it injected
em.getTransaction().begin();//only if resource-local persistence unit. Otherwise if JTA: open the transaction the JTA-specific way (if that was not already done by the container)
Product product = em.find(Product.class, productId);
for (Feature crtFeature : product.getFeatures()) {
    if (!em.contains(crtFeature)) {
       throw new RuntimeException("Feature is not managed, so removeOrpahns cannot work");
    }
}
product.getFeatures().clear();

Feature feature = new Feature(product, ls);
em.persist(feature);//you need this, as there is no cascading from Product to Feature.
product.getFeatures().add(feature);

em.getTransaction().commit();//if you work with a resource-local persistence unit. Otherwise if JTA: commit the transaction the JTA-specific way (if that was not already done by the container)
4
  • This is essentially what I am doing already - clearing the collection on the parent object, and adding a new entity instance to the collection afterwards. The new instance is added, but the old ones are not removed from the collection. Aug 12, 2014 at 6:18
  • @DennisThrysøe May be you missed the most important thing: those entities MUST be fetched both the Product and Features (in the same transaction) and the transaction MUST be committed (either manually, or by the container). Also check my changed example that will throw an exception, if any of those features to be removed are not managed. Make sure that everything is done in a transaction and that the transaction is committed (e.g simply change some other changed fields of the Product in order to make sure that ANYTHING is saved)!
    – V G
    Aug 12, 2014 at 8:34
  • It is done in a transaction. The added items are committed properly. I could not add the new features without having fetched the Product entity first. The Feature entities are also fetched as I iterate them explicitly. Aug 13, 2014 at 7:37
  • I can confirm that this code does also not work. The extra feature is added, but nothing is removed from the feature table in the database. Code used as-is except for the transaction management, which is done by my container. The features field on the Product entity has the cascade parameter set as specified. Aug 14, 2014 at 11:13
0

In Section 2.9, Entity Relationships, the JPA 2.1 spec says:

If the entity being orphaned is a detached, new, or removed entity, the semantics of orphanRemoval do not apply.

Are you sure that your entity is managed in the persistence context when removing it from collection?

You can fix it by using fetch=fetchType.EAGER or by fetch joins. Alternatively (it depends on your use case), it may be sufficent to set appropriate cascade option.

3
  • I tried a number of cascade options. I also tried eager fetching. My goal is to remove/delete all previous entities in the collection, and adding some new instead. But none are deleted, even though the new items are added. Jul 13, 2014 at 20:07
  • @DennisThrysøe which version of Hibernate and JPA are you using? Are you sure that dependent entities are in persistence context? Can you simply access these objects via listCollection.get(0).getSomething()? Jul 13, 2014 at 20:10
  • Hibernate version 3.6.10. Yes, I can use the collection elements directly without problems. Jul 15, 2014 at 16:43
0

I faced a similar problem recently. For me, the issue was that the orphans were still referenced from another managed entity, and there was a PERSIST cascading defined for that relationship:

// Parent entity
@OneToMany(mappedBy = "product", orphanRemoval = true)
private List<Feature> features = new ArrayList<>();

// Child entity
@ManyToOne
private Product product;

@ManyToOne
private Description description;

// Another entity (let's say descriptions can be shared between features)
@OneToMany(mappedBy = "description", cascade = CascadeType.PERSIST)
private List<Feature> features = new ArrayList<>();

Assume that all of the involved entities are managed, i.e. loaded into the persistence context. Now we do the same thing as the OP:

// Clear and add attempt
product.getFeatures().clear();

Feature feature = new Feature(product, ls);
product.getFeatures().add(feature);

Philosophically, the issue here is that the object model becomes inconsistent if you only remove the Feature from the Product entity, but not from the Description entity. After all, you want the Feature to be removed, but it is still being referenced from other objects. Technically, what happens is that there are two conflicting cascadings going to the Feature entity, and the result may depend on the order in which they are applied.

Since the Feature was removed from the collection in product, the orphan removal applies, and the Feature entity transitions to "removed" state during the next flush, as stated in the JPA 2.1 spec (2.9). I added emphasis on the relevant parts:

Associations that are specified as OneToOne or OneToMany support use of the orphanRemoval option. The following behaviors apply when orphanRemoval is in effect:

  • If an entity that is the target of the relationship is removed from the relationship (by setting the relationship to null or removing the entity from the relationship collection), the remove operation will be applied to the entity being orphaned. The remove operation is applied at the time of the flush operation. The orphanRemoval functionality is intended for entities that are privately “owned” by their parent entity. Portable applications must otherwise not depend upon a specific order of removal, and must not reassign an entity that has been orphaned to another relationship or otherwise attempt to persist it. If the entity being orphaned is a detached, new, or removed entity, the semantics of orphanRemoval do not apply.

However, the same Feature is still referenced from a Description entity, which has a PERSIST cascading towards the Feature. The JPA 2.1 spec says the following:

The semantics of the flush operation, applied to an entity X are as follows:

  • If X is a managed entity, it is synchronized to the database.

    • For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value cascade=PERSIST or cascade=ALL, the persist operation is applied to Y.

So this cascading will perform a "persist" operation on the Feature entity, even if we don't call em.persist() on the Description. It is enough for the Description to be managed when a flush is performed to trigger this persist cascading.

This means we are doing exactly what the spec told us we shouldn't - performing orphan removal and persisting on the same entity. What seems to happen in practice in Hibernate is that both operations are applied in turn. First the remove operation makes the Feature entity transition to "removed" state, then the persist operation turns the removed entity back into a managed one. As a result, the Feature is not removed from the database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.