Sujit
Sujit

Reputation: 476

Save data to database via Spring Data repository

I am planning to store data from multiple tables which has one to many JPA relationship. I am creating my Repository interface which extends from JPARepository. My question is If I want to save a data on Many sides of relationship (in the below scenario it's Tour) then shall I do with TourRepository or PersonRespository?

On a similar note Is it ideal to create individual repository classes for every JPA entities where data need to be stored? or any better way with limited repository classes the data store to database can be achieved?

@Entity
@Table(name="Person")
public class Person implements Serializable{
...
...
@OneToMany(mappedBy = "person")
private List<Tour> tours;
...



@Entity
@Table(name = "Tour")
public class Tour implements Serializable{
...
...
@ManyToOne
@JoinColumn(name = "PERSON_ID")
private Person person;
...

Upvotes: 1

Views: 4738

Answers (3)

Cepr0
Cepr0

Reputation: 30309

You have two independent entities. Person can exist without Tour and Tour can exist without Person. So you should have two repositories - for Person and Tour to store their data independently:

Tour tour1 = new Tour("tour1");
tourRepo.save(tour1);

Person person1 = new Person("person1");
person1.addTour(tour1);
personRepo.save(person1);

You chose the bidirectional one-to-many association so you have to use a 'helper' method like addTour to link both entities:

public Person addTour(Tour tour) {

    tour.setPerson(this);
    this.tours.add(tour);
    return this;
} 

Additional info: Best Practices for Many-To-One and One-To-Many Association Mappings

Upvotes: 1

Ajit Soman
Ajit Soman

Reputation: 4074

I would suggest you to use CascadeType.ALL on @OneToMany mapping in Person entity:

@OneToMany(mappedBy = "person",cascade = {CascadeType.ALL})
private List<Tour> tours;

And then create repository for person to save person object with the list of tours .

CascadeType.ALL means persistence will propagate all EntityManager operations like PERSIST, REMOVE, REFRESH, MERGE, DETACH to the relating entities.

Upvotes: 1

ThanhLoyal
ThanhLoyal

Reputation: 393

Add cascade to tours:

@OneToMany(mappedBy = "person", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private List<Tour> tours;

When you save person object, his tours will be saved automatically.

By the way, in Person class, you should have an addTour(...) utilities method like this:

// Person.java

public void addTour(Tour tour){
    this.tours.add(tour);
    tour.setPerson(this);
}

Upvotes: 1

Related Questions