java避免了Spring数据类中重复的SQL代码
Spring数据有自己的注释“Query”,它将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 楼答案
只需对查询使用静态字符串,如