1

Well, I have a Restaurant Entity with an Element Collection of Branches . Now my question is how do I remove a branch from a restaurant since an Embeddable object doesn't have an Id . Usually, what i would do If branch was an entity is

entityManager.remove(entityManager.getReference(Branch.class, branchId));

But since Branch is Embeddable object (without ID), I am not sure how to achieve it . Some code examples would be highly appreciated. Thanks in advance.

adn.911
  • 1,256
  • 3
  • 17
  • 30
  • You find the branch you want to remove in the collection, and then remove it from the collection. That said, you should probably make Branch an entity. – JB Nizet May 05 '15 at 16:54
  • @JBNizet I know i could use Branch as an entity. But if that is the case, then when should we use an Embeddable element collection anyways??? I thought a Restaurants Branches was a perfect candidate for embeddable object, Since a restaurant has a list of Branches and Branch can't exist without it's restaurant , .. – adn.911 May 05 '15 at 17:12
  • That doesn't mean it doesn't have an identity. That doesn't mean you don't want to view, create, modify, or delete branches. I've never had a use-case where a collection of embeddables looked like a good idea to me. That basically boils down to having a table without primary key, which I also see as a horrible idea. – JB Nizet May 05 '15 at 17:59

1 Answers1

0

You need to identify the object you want to remove (obviously without id since there is none, but the combination of other fields should be unique), remove it from owner entity's collection and merge the entity.

Since there is no id, JPA will delete all elements from collection, and insert them again but without the removed one.

Branch toBoRemoved = ...; // find out which element needs to be removed
for (Iterator i = entity.getBranches().iterator(); i.hasNext();) {
    Branch b = (Branch)i.next();
    if (b.equals(toBeRemoved)) {  // you'll need to implement this
        i.remove();
    }
}
entityManager.merge(entity);
Predrag Maric
  • 23,938
  • 5
  • 52
  • 68
  • So, that makes Embedabble elements really bad for performance, than why should we use Embeddable element collection in the first place ??? Should i just make it an Entity ??? – adn.911 May 05 '15 at 17:02
  • Yes, you should probaly make it an entity. – Predrag Maric May 05 '15 at 17:08
  • Can I just use an hql query to remove the branch with it's name ? – adn.911 May 05 '15 at 17:18
  • Haven't tried but i dn't think it will work because it only works with entities. However, look at this posthttp://stackoverflow.com/a/3743149/4074715 there is a workaround for Hibernate using `@OrderColumn` – Predrag Maric May 05 '15 at 17:33