Reputation: 19
I am using spring data and have two entities with a OneToMany and ManyToOne relationship between eachother respectively. I want the relationship to function simply as a foreign key reference and nothing more however when I save contact data it also saves all data under Person and its relations which I do not want. I just want it to link the person entity to the contact entity and nothing more. I tried many things including different Cascade types and removing cascade alltogether.
@Entity
@Table(name = "person")
public class Person {
@Id
@GeneratedValue
public UUID person_id;
@OneToMany(mappedBy = "person")
public List<Contact> contacts;
...etc
}
@Entity
@Table(name = "contact")
public class Contact {
@Id
@GeneratedValue
public UUID contact_id;
@ManyToOne
@JoinColumn(name = "person_id")
public Person person;
...etc
}
Upvotes: 1
Views: 789
Reputation: 339
If you want to remove all cascading, just use CascadeType.
https://www.baeldung.com/jpa-cascade-types
Upvotes: 1
Reputation: 1036
When you save a contact data for a specific person record, that person record must already exist if you declare the domain objects as described in your question. So you are going to do like:
Person person = personRepository.findOne(personId);
contact.setPerson(person);
contactRepository.save(contact);
This simply creates a relationship (a foreign key), and adds the primary key of the specified person to the newly created contact record. Nothing is changed in the person record.
Upvotes: 0