如何在Spring Boot Data Jpa应用程序中使用Criteria查询 [英] How to use Criteria Queries in Spring Boot Data Jpa Application

查看:812
本文介绍了如何在Spring Boot Data Jpa应用程序中使用Criteria查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an application that uses Spring Boot Data jpa . So far i am using a repository like this

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

如何使用 Criteria Query Hibernate在Spring Boot应用程序中提供这种情况

How can i make use of Criteria Query That Hibernate Provides for such cases in a Spring Boot Application

推荐答案

docs

From the docs


为了丰富具有自定义功能的存储库,您首先需要为自定义功能定义一个接口和一个实现。使用您提供的存储库接口来扩展自定义接口。

To enrich a repository with custom functionality you first define an interface and an implementation for the custom functionality. Use the repository interface you provided to extend the custom interface.

定义一个类似于这样的接口

Define an interface like so

public interface StudentRepositoryCustom {

    List<String> nameByCourse(String coursename);

}

然后像这样定义这个接口的自定义实现 p>

Then define a custom implementation of this interface like so

@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.
    }

}

现在您可以扩展此自定义存储库

Now you can extend this custom repository implementaion in your JPA repository like so.

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

}

详细了解条件查询和条件生成器 here

Learn more about criteria query and criteria builder here

这篇关于如何在Spring Boot Data Jpa应用程序中使用Criteria查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆