0

I want to automatically persist/merge Address entities of persons. Once created, they should be updateable by any person, but not removed if a Person is removed.

//each person can only have one address
@Entity
public class Person {
    @ManyToOne
    private Address address;
}


//one address can be assigned to multiple persons (eg family members)
@Entity
public class Address {
    @OneToMany
    private List<Person> persons;
}

Questions:

  1. How would I have to write the cascade annotations for this requirement?
  2. How would I create those entities? person.setAddress(address) or address.getPersons().add(person)?
membersound
  • 81,582
  • 193
  • 585
  • 1,120

2 Answers2

0

I think the @Cascade({CascadeType.MERGE}) on both would be what you are looking for.

I would probably create and persist a Person without an address, and then in the Address entity have something like:

public void addPerson(Person person) {
   persons.add(person);
   person.setAdderess(this);
}

Hope this helps.

Nicholas Robinson
  • 1,359
  • 1
  • 9
  • 20
0
  1. To answer your first question, for your desired requirement you should use cascade=CascadeType.REMOVE to avoid removing an Address if a Person is removed:
@OneToMany(cascade = CascadeType.REMOVE mappedBy = "person")

You may take a look at this article it explains the same behavior in the same situation, saying that:

If only cascade=CascadeType.REMOVE is specified no automatic action is taken since removing a relationship is not a remove operation.

  1. For the second question to persist both entities you should use the two statements together, like this:
person.setAddress(address);
address.getPersons().add(person);

Take a look here for further information.

Community
  • 1
  • 1
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
  • Are you sure about adding the `CascadeType.REMOVE`. Shouldn't this be the only cascade type the should be *left* out, so that the remove is *not* cascaded? – membersound Aug 18 '15 at 09:44
  • As it says in the article: *If only cascade=CascadeType.REMOVE is specified no automatic action is taken since removing a relationship is not a remove operation.* – cнŝdk Aug 18 '15 at 09:46
  • Don't take it out of the context. The sentense refers to the statement before with `orphanRemoval=true`: *If orphanRemoval=true is specified the removed address instance is automatically removed. If only cascade=CascadeType.REMOVE is specified no automatic action is taken since removing a relationship is not a remove operation.* – membersound Aug 18 '15 at 09:54
  • And what does that mean? They are separtaed sentences! – cнŝdk Aug 18 '15 at 09:57