Search code examples
spring-bootspring-data-jpaspring-datahibernate-mapping

How to bind @PathVariable value to @Where clause in Spring boot rest API


I am reading @PathVaraible in Controller and using @Where annotation in Entity. If I pass hardcoded value to @Where clause in Entity it is working fine. But I want to pass run time value which is passed in @PathVariable to @Where in Entity.

@GetMapping("/api/v1/course/details/{courseId}")
    public List<CourseDto> getcourseDetails(@Valid @PathVariable final String courseId) {
        // lines of code
        }

@Entity
@Where(clause="course_id=:courseId")
public class CourseEntity{
@NotBlank(message = "Please provide courseId)
    @Getter
    @Setter
    @Column(columnDefinition = "nvarchar(50)",length = 50)
    private String courseId;

}

@Repository
public interface MyRepo extends JpaRepository<Course, Integer> {
 

}

With this code I am getting error as

Incorrect syntax near ':'.

How to fix this error. Is there any other solution ?


Solution

  • You cannot change a @Where clause at runtime. If you want to set a parameter you can use @Filter:

    @Entity
    @FilterDef(
        name="courseFilter",
        parameters=@ParamDef(
            name="courseId",
            type="int"
        )
    )
    @Filter(
        name="firstAccounts",
        condition="course_id=:courseId"
    )
    public class CourseEntity{
       ...
    }
    

    Now with the Hibernate ORM session or entity manager you can set a parameter the following way:

    entityManager
        .unwrap( Session.class )
        .enableFilter( "courseFilter" )
        .setParameter( "courseId", ...);
    
    List<CourseEntity> courses = entityManager
        .createQuery("from CourseEntity c", CourseEntity.class)
        .getResultList();
    

    The Hibernate ORM documentation has more details about filtering entities using @Filter or @Where.