As the title described, I’m having trouble in selecting only the data I want from a database given my entity classes:
@Entity(name = "Movie")
@Table(name = "movie")
public class Movie implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Size(max = 300)
@Column(name = "title", nullable = false, length = 300)
private String title;
@NotBlank
@Size(max = 1000)
@Column(name = "description", nullable = false, length = 1000)
private String description;
@ManyToMany(targetEntity = Genre.class, fetch = FetchType.LAZY, cascade = {CascadeType.REFRESH})
@JoinTable(name = "movie_genres",
joinColumns = @JoinColumn(name = "movie_id", referencedColumnName = "id", nullable = false),
inverseJoinColumns = @JoinColumn(name = "genre_id", referencedColumnName = "id", nullable = false))
private List<Genre> genres = new ArrayList<>();
//Constructors, getters and setters excluded for brevity
}
@Entity(name = "Genre")
@Table(name = "genre")
public class Genre implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Size(max = 300)
@Column(name = "name", nullable = false, length = 300)
private String name;
//Constructors, getters and setters excluded for brevity
}
Is there a way to write a Spring Data JPA repository method that returns all paged movies, with only id
and title
selected (without description
), and genres
eagerly loaded in this case alone? Something akin to this method:
List<Movie> findAll(Pageable pageable);
Note that i wish for it to return a List
, and not Page
, as Page
makes another count request to the database, which I don’t need. I am using Spring Boot version 3.3, with spring-boot-starter-data-jpa
and spring-boot-starter-web
as dependencies. My database is MySQL.
I tried everything, from reading the Spring Data JPA User Guide, to trying different combinations with @Query
and @EntityGraph
, only for it to not compile at all, or to favour only one of them, selecting all eager data including description
.
For instance the following does not compile as it does not recognize the constructor, even though I have such constructor in Movie entity:
@Query("SELECT new Movie(m.id,m.title,m.genres) FROM Movie m")
List<Movie> findAllPageable(Pageable pageable);
6