gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:06:07 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com