Search code examples
jpacomposite-key

Build method in JPA with composite key


This is my entity with composite key:

@Entity
@Table(name = "course_ratings")
public class CourseRating {
    @EmbeddedId
    private CourseRatingKey id;
}

Where CourseRatingKey looks like this:

@Embeddable
public class CourseRatingKey implements Serializable {
    @Column(name = "user_id")
    private int userId;

    @Column(name = "course_id")
    private int courseId;

    public CourseRatingKey() {
    }
    
    // getters, setters, equals(), hashCode()
}

And my JPA repository

@Repository
public interface CourseRatingRepository extends JpaRepository<CourseRating, CourseRatingKey> {

}

I am trying to build method that will return list of all CourseRating with given courseId property of CourseRatingKey. Below method doesn't work because JPA doesn't recognize it:

repository.findAllByIdCourseId(int id);

How can I build my method name to achieve my goal?


Solution

  • I have solved my problem by declaring this method in repository. I'm a bit confused as the other methods work without declaring.

    @Repository
    public interface CourseRatingRepository extends JpaRepository<CourseRating, CourseRatingKey> {
    
        List<CourseRating> findAllByIdCourseId(Integer id);
    }