Spring 数据中 return 不同的相同查询方法和参数

Same query method and parameters with different return in Spring Data

我想使用投影,以便 return 相同查询的元素更少。

Page<Network> findByIdIn(List<Long> ids);
Page<NetworkSimple> findByIdIn(List<Long> ids);

由于查询是使用方法名称创建的,我必须使用哪些选项来执行相同的查询但名称不同?

Spring 通过方法进行数据查询是按照惯例构造的,您不能更改名称但期望相同的行为。

您可以尝试使用不依赖于方法名称的@Query 注释,或者可能使用 JPAQuery 加 FactoryExpression 实现自定义 DAO,它与投影具有相同的效果。

我今天运行进入这个,接受的答案实际上是不正确的;您可以 更改方法名称而不改变行为。根据 Spring 数据文档:

Any text between find (or other introducing keywords) and By is considered to be descriptive unless using one of the result-limiting keywords such as a Distinct to set a distinct flag on the query to be created or Top/First to limit query results.

因此你可以有一个名为 findByIdIn 的方法和另一个名为 findNetworkSimpleByIdIn 的方法,这两个方法将 return 相同的数据(可以根据定义的 return类型)。