springspring-bootspring-data-jpasessionfactory

How to convert SessionFactory query to JPA query?


I am converting a plain Spring application to Spring with SpringBoot.

There are some places in the code where they have queries using SessionFactory:

public List<Enrollment> findByOrganizationAndYear(Organization organization, int year) {

    String queryString = "from Enrollment as enrollment where enrollment.organization.id = :organizationId AND YEAR(enrollment.event.fromDate) = :year";
    Query query = sessionFactory.getCurrentSession().createQuery(queryString);
    query.setParameter("organizationId", organization.getId());
    query.setParameter("year", year);

    return query.list();

}

How can i convert this to a plain JPA query ? Or do i need to write a custom @Query ?

Thank you.


Solution

  • I think that the @Query annotation has more flexibility.

    public interface EnrollmentRepository extends Repository<Enrollment, Long> {
    
        // Spring Data query with field names 
        List<Enrollment> findByOrganizationAndEventFromDate(Organization organization, int year);
    
        // Or you can write your custom query 
        @Query("select e from Enrollment e where e.organization.id = :organizationId and e.event.fromDate = :year")
        List<Enrollment> findAll(@Param("organizationId") Long organizationId, @Param("year") int year);
    
    }