I am new to Spring Data JPA, so I am having a trouble writing queries. I want to get all actors that had role in a certain movie that I get from movieID.
When trying this, I get error while trying to start :
Validation failed for query for method public abstract java.util.List
@Repository
public interface RoleRepository extends JpaRepository<RoleEntity, Long> {
@Query(value = "select distinct r.actor from RoleEntity r " +
"where r.movie.movieID = ?1")
List<ActorEntity> findByMovieID(Long movieID);
}
Here are my entities:
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity(name = "roles")
public class RoleEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long roleID;
@ManyToOne
@NotNull
@JoinColumn(name = "actor_id", referencedColumnName = "id")
private ActorEntity actor;
@ManyToOne(fetch = FetchType.LAZY)
@NotNull
@JoinColumn(name = "movie_id", referencedColumnName = "id")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
private MovieEntity movie;
private String roleName;
}
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Table(name="actor")
public class ActorEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long actorID;
@NotEmpty
private String firstName;
@NotEmpty
private String lastName;
@Enumerated(EnumType.STRING)
private Gender gender;
@OneToMany(mappedBy = "actor", cascade = CascadeType.ALL)
@JsonBackReference
private Set<RoleEntity> roles = new HashSet<>();
}
@Getter
@Setter
@ToString
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "movie")
public class MovieEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long movieID;
@NotEmpty
private String name;
@NotEmpty
private String description;
@NotEmpty
private String duration;
@NotNull
private LocalDate startTime;
private LocalDate endTime;
@OneToMany(mappedBy = "movie", cascade = CascadeType.ALL)
private Set<RoleEntity> roles = new HashSet<>();
@OneToMany(mappedBy = "movie", cascade = CascadeType.ALL)
private Set<ProjectEntity> projects = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "movie_genres",
joinColumns = @JoinColumn(name = "movie_id"),
inverseJoinColumns = @JoinColumn(name = "genre_id"))
private Set<GenreEntity> genres;
}
I tried using native query, but it says it returns Long?!
@Query(value = "select a.id, a.first_name, a.last_name, a.gender " +
"from actor a " +
"join roles r on r.actor_id = a.id " +
"where r.movie_id = ?1", nativeQuery = true)
List<ActorEntity> findByMovieID(Long movieID);
Thank you very much in advance!!! 😀