java - 避免 Spring 数据类中出现重复的 SQL 代码

标签 java spring spring-data-jpa spring-data

Spring data 有自己的注释“Query”,它将 SQL 查询与 Java 关联起来。它通常对存储库中的每个方法使用一个查询。

我的问题:Spring Data是否有办法编写一次查询并多次使用它?

例如,替换此代码

@Repository
public interface StuffRepository extends JpaRepository<Stuff, Integer>, JpaSpecificationExecutor<Stuff> {


    @Query(value = "SELECT s "
        + "FROM Stuff s "
        + "JOIN s.foo f"
        + "WHERE f.id = :id")
    Page<Stuff> findByFooId(@Param("id") String id,  Pageable pageable);

    @Query(value = "SELECT s "
        + "FROM Stuff s "
        + "JOIN s.foo f"
        + "WHERE f.id = :id")
    List<Stuff> findByFooId(@Param("id") String id);

    @Query(value = "SELECT s "
        + "FROM Stuff s "
        + "JOIN s.foo f"
        + "WHERE f.id = :id")
    Stuff findByFooIdFirst(@Param("id") String id);
}

像这样的事情

@Repository
public interface StuffRepository extends JpaRepository<Stuff, Integer>, JpaSpecificationExecutor<Stuff> {


    @Query(value = "SELECT s "     //create query findByFooId
        + "FROM Stuff s "
        + "JOIN s.foo f"
        + "WHERE f.id = :id",
        name = "findByFooId"
    )
    Page<Stuff> findByFooId(@Param("id") String id,  Pageable pageable);

    @Query(name = "findByFooId")   // link to query
    List<Stuff> findByFooId(@Param("id") String id);



    @Query(name = "findByFooId")   //link to query
    Stuff findByFooIdFirst(@Param("id") String id);
}

最佳答案

只需使用静态字符串进行查询即可

@Repository
public interface StuffRepository extends JpaRepository<Stuff, Integer>, JpaSpecificationExecutor<Stuff> {


String QUERY = "SELECT s "    
    + "FROM Stuff s "
    + "JOIN s.foo f"
    + "WHERE f.id = :id";

@Query(value = QUERY)   
List<Stuff> findByFooId(@Param("id") String id);


@Query(value= QUERY)   
Page<Stuff> findByFooId(@Param("id") String id,  Pageable pageable);

关于java - 避免 Spring 数据类中出现重复的 SQL 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50949194/

相关文章:

java - 如何使用 CrudRepository 按组合字段排序?

java - 有没有办法以编程方式启动eclipse导出功能

java - 如何使用 Java 查找 Exchange 服务器版本?

java - 向 HttpServletRequest 添加额外参数

java - 如何在 Spring Boot 中将 JSON HashMap 绑定(bind)到 @RequestBody

java - Spring框架-如何将目录作为资源注入(inject)?

java - 尝试按 JPA Spring Boot 中的嵌套字段排序时 OrderBy 不起作用

java - spring boot starter security post 方法不起作用

java - eclipse 中的 build.xml 不构建 jar

c# - 不完整的消息(C# TCP/IP 客户端)