I am trying to get familiar with spring and jpa. For start there is a table anime_details containing details of an anime. As it can have many genres, db has another table named genre. The intermediate table to contain their many to many relationship entries is also there. When I query for any anime by id, it should return the details of the anime along with the genres.
It does return an object with details of the anime and list of Genre objects (which is as expected). But what I want is to restrict the columns that will be fetched from Genre objects. For example only id or just id and name (In case there are more columns other than these).
AnimeDetails
@Getter
@Setter
@Entity
@Table(name = "anime_details")
public class AnimeDetails {
@Id
@SequenceGenerator(name = "animeDetailsSeq", sequenceName =
"anime_details_id_seq",
allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator =
"animeDetailsSeq")
private Integer id;
private String name;
private Integer episodes;
private Date started;
private Date ended;
private String status;
@ManyToMany
@JoinTable(
name = "anime_genre",
joinColumns = @JoinColumn(name = "details_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "genre_id", referencedColumnName = "id"))
@JsonManagedReference
private List<Genre> genres;
protected AnimeDetails() {
}
}
Genre
@Data
@Entity
@Table(name = "genre")
public class Genre {
@Id
@SequenceGenerator(name = "genreSeq", sequenceName = "genre_id_seq",
allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "genreSeq")
private Integer id;
private String name;
@ManyToMany(mappedBy = "genres")
List<AnimeDetails> animes;
protected Genre() {
}
}
Expected payload
{
"id": 2,
"name": "Your Name",
"episodes": 1,
"started": "2016-08-25T18:00:00.000+0000",
"ended": "2016-08-25T18:00:00.000+0000",
"status": "Completed",
"genres": [
{
"id": 5,
"name": "Drama"
},
{
"id": 10,
"name": "Supernatural"
}
]
}
Right now, I get the result and manually get columns one by one and set those in a DTO. But that is not efficient as the database query is already fetching more data than needed. Is there any specific annotation/property/jpql to reduce it?