小编典典

如何在Spring Boot Data Jpa应用程序中使用条件查询

spring-boot

我有一个使用 Spring Boot Data jpa 的应用程序。到目前为止,我正在使用这样的存储库

public interface StudentRepository extends CrudRepository<StudentEntity, Integer>{
    @Query(value = "" 
        + "SELECT s.studentname "
        + "FROM   studententity s, "
        + "       courseentity c "
        + "WHERE  s.courseid = c.courseid "
        + "       AND s.courseid IN (SELECT c.courseid "
        + "                          FROM   courseentity c "
        + "                          WHERE  c.coursename = ?1)")
    List<String> nameByCourse(String coursename);
}

我如何在Spring Boot应用程序中利用Hibernate为此类情况提供的 条件查询


阅读 298

收藏
2020-05-30

共1个答案

小编典典

来自 docs

要使用自定义功能丰富存储库,您首先要定义自定义功能的接口和实现。使用您提供的存储库界面扩展自定义界面。

像这样定义一个接口

public interface StudentRepositoryCustom {

    List<String> nameByCourse(String coursename);

}

然后像这样定义此接口的自定义实现

@Service
class StudentRepositoryImpl implements StudentRepositoryCustom {

    @PersistenceContext
    private EntityManager em;

    public List<String> nameByCourse(String coursename) {            
        CriteriaBuilder cb = em.getCriteriaBuilder();
        //Using criteria builder you can build your criteria queries.
    }

}

现在,您可以像这样在JPA存储库中扩展此自定义存储库实现。

public interface StudentRepository extends CrudRepository<StudentEntity, Integer>, StudentRepositoryCustom {

}

了解有关条件查询和条件构建器的更多信息 here

2020-05-30