【问题标题】:Spring data couchbase documents java classes inheritanceSpring数据couchbase文档java类继承
【发布时间】:2018-09-15 03:15:36
【问题描述】:

我的问题是,spring data couchbase 不会搜索搜索到的类的子类。例如:

型号:

@Document 
class A { 
   @Id
   String id 
}

@Document
class B extends A {}

和存储库:

public interface ARepository extends PagingAndSortingRepository<A, String>{
     Page<A> findAll(Pageable pageable);
}

Spring data couchbase 生成查询,条件为 where

_class="com.example.model.A"

但我也想在这个查询中搜索 B 文档。是某种方式,我该怎么做?当我编写自己的查询时,我必须在查询中定义顺序、限制和偏移量,并且不使用 Pageable。但我想使用 Pageable。

【问题讨论】:

标签: java spring inheritance couchbase spring-data-couchbase


【解决方案1】:

考虑基于继承的通用接口。

首先创建超类:

@Inheritance
public abstract class SuperClass{ 

  @Id
  private int id;
}

然后创建你的子类:

public class A extends SuperClass { /* ... */ }
public class B extends SuperClass { /* ... */ }

创建基础存储库:

@NoRepositoryBean
public interface SuperClassBaseRepository<T extends SuperClass> 
extends PagingAndSortingRepository<T, Integer> { 
     public T findAll();

}

然后基于基础 repo 创建 SuperClass 存储库:

@Transactional
public interface SuperClassRepository extends SuperClassBaseRepository<SuperClass> { /* ... */ }

@Transactional
public interface ARepository extends SuperClassBaseRepository<A> { /* ... */ }

@Transactional
public interface BRepository extends SuperClassBaseRepository<B> { /* ... */ }

SuperClassRepository findAll() 将搜索所有 A 和 B 类

【讨论】:

  • 感谢您的帮助,但这只能在 Spring Data JPA 中实现。 Spring data couchbase 没有 @Inheritance 注释。 spring data couchbase 中的内容是否相同?
【解决方案2】:

我们设法在 Spring Data Couchbase 3.2.12 上完成了这项工作。这是我们所做的:

我们发现每种类型的映射器只有在存在该类型的存储库时才会创建,因此,除了我们的超类存储库...

public interface ARepository extends PagingAndSortingRepository<A, String> {
     Page<A> findAll(Pageable pageable);
}

我们为每个子类型创建了一个空存储库,例如:

public interface BRepository extends PagingAndSortingRepository<B, String>{
     // No methods
}

第二个 repo 的存在保证了 B 的适当映射器的存在,因此当在 ARepository 中调用 findAll(或其他方法)时,每个子类的映射器都存在。完成此操作后,我们能够获得实际上是 B 实例的 A 列表。

希望这会有所帮助,没有人会再为此浪费时间。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-03
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    相关资源
    最近更新 更多