如何将会话工厂查询转换为 JPA 查询?



我正在使用SpringBoot将一个普通的Spring应用程序转换为Spring。

代码中的某些地方他们使用 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();
}

如何将其转换为普通的 JPA 查询?还是我需要编写自定义@Query?

谢谢。

我认为@Query注释具有更大的灵活性。

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);
}

最新更新