【问题标题】:How to convert SessionFactory query to JPA query?如何将 SessionFactory 查询转换为 JPA 查询?
【发布时间】:2020-10-21 02:19:59
【问题描述】:

我正在使用 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 ?

谢谢。

【问题讨论】:

    标签: spring spring-boot spring-data-jpa sessionfactory


    【解决方案1】:

    我认为@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);
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-13
      • 2012-09-28
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      相关资源
      最近更新 更多