Reputation: 426
I'm using a Spring Boot web service, and i want to know the best way to manipulate the data the relationships between the entities.
The first method is using bidirectional relationships like the following:
Title entity :
@Entity
public class Title {
private Integer id;
private String name;
private List<TitleCelebrity> titleCelebrities;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Basic
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(mappedBy = "title", cascade = CascadeType.ALL)
public List<TitleCelebrity> getTitleCelebrities() {
return titleCelebrities;
}
public void setTitleCelebrities(List<TitleCelebrity> titleCelebrities) {
this.titleCelebrities = titleCelebrities;
}
}
TitleCelebrity entity :
@Entity
@Table(name = "title_celebrity")
public class TitleCelebrity {
private Integer id;
private String type;
private Title title;
@Id
@Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Basic
@Column(name = "type")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "title_id")
@JsonIgnore
public Title getTitle() {
return title;
}
public void setTitle(Title title) {
this.title = title;
}
}
so each time i make a request to get a title, i got the Title with the list of TitleCelebrity, and that's what i want.
now the other way is not to use bidirectional relationship, instead make two queries, the first is to get the Title and based on that Title id i make second query to get the TitleCelebrity.
i prefer the second way, but is it the best way to go ?
Upvotes: 0
Views: 611
Reputation: 202
Why opt for the more resource demanding option? If you go with the latter option at least use a join. Executing two queries instead of letting the database handle it all at once is unnecessarily wasting resources.
Also, let your ORM (hibernate) handle the basic queries like this. There's really no reason to write out the queries yourself.
Upvotes: 1