避免在Spring数据类中重复SQL代码

时间:2018-06-20 13:16:43

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

Spring数据具有其自己的注释“查询”,该注释将SQL查询与Java关联。在存储库中,每种方法通常会使用一个查询。

我的问题:spring数据是否可以编写一次查询并将其乘以多次?

例如,替换此代码

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

1 个答案:

答案 0 :(得分:1)

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

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