如何将 SessionFactory 查询转换为 JPA 查询?
How to convert SessionFactory query to JPA query?
我正在使用 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);
}
我正在使用 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);
}