简体   繁体   English

从 Spring 数据 JPA 查询方法返回自定义集合

[英]Return custom collection from Spring Data JPA query method

I would like my custom query method to return a specific Guava collection type ( ImmutableSet in my example).我希望我的自定义查询方法返回特定的 Guava 集合类型(在我的示例中为ImmutableSet )。

Example:例子:

public interface MyRepository extends CrudRepository<User,UserId> {

  @Query("SELECT DISTINCT u FROM User u WHERE... ORDER BY ...")
  ImmutableSet<User> findByxxxx();

}

When I try it, I get:当我尝试时,我得到:

Failed to convert from type [java.util.ArrayList<?>] to type [com.google.common.collect.ImmutableSet<?>]
...
Caused by: java.lang.IllegalArgumentException: Could not instantiate Collection type: com.google.common.collect.ImmutableSet

The documentation does not explicitly list the Guava collection types, so I am not sure if it is impossible without a new release, or if there is some configuration that is possible to make it work. 文档没有明确列出 Guava 集合类型,所以我不确定如果没有新版本是不可能的,或者是否有一些配置可以使它工作。

How can I instruct Spring Data JPA to use that type?如何指示 Spring 数据 JPA 使用该类型?

Spring data doesn't support collections from any third-party libraries and probably never do... Spring 数据不支持来自任何第三方库的 collections 并且可能永远不会支持...

CrudRepository exposes an Iterable to you and if you want to materialize to custom collection it's up to you to do that. CrudRepository向您公开一个Iterable ,如果您想实现自定义集合,则由您来做。

By the way If you want your repository returns custom collection types you can decorate the spring data repository with yours.顺便说一句,如果您希望您的存储库返回自定义集合类型,您可以使用您的来装饰 spring 数据存储库。 Like this像这样

interface JpaUserRepository extends CrudRepository<User,UserId> {

  @Query("SELECT DISTINCT u FROM User u WHERE... ORDER BY ...")
  Iterable<User> findByxxxx();

}
public class MyRepository {

   private final JpaUserRepository jpaUserRepository;

   @Autowired
   public MyRepository(final JpaUserRepository jpaUserRepository) {
     this.jpaUserRepository = jpaUserRepository;
   } 

   public ImmutableSet<User> findByxxxx() {
     return ImmutableSet.copyOf(jpaUserRepository.findByXXX());
   }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM