我的问题是,Spring数据库不会搜索搜索类的子类。例如:
型号:
@Document
class A {
@Id
String id
}
@Document
class B extends A {}
和存储库:
public interface ARepository extends PagingAndSortingRepository<A, String>{
Page<A> findAll(Pageable pageable);
}
Spring数据沙发库生成查询,即具备在哪里条件
_class="com. example.model.A"
但是我也想在这个查询中搜索B文档。是某种方式,我怎么能做到这一点?当我编写自己的查询时,我必须在查询中定义顺序、限制和偏移量,并且不使用分页。但是我想使用分页。
考虑基于继承的通用接口。
首先创建超类:
@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();
}
然后基于base repo创建SuperClass存储库:
@Transactional
public interface SuperClassRepository extends SuperClassBaseRepository<SuperClass> { /* ... */ }
@Transactional
public interface ARepository extends SuperClassBaseRepository<A> { /* ... */ }
@Transactional
public interface BRepository extends SuperClassBaseRepository<B> { /* ... */ }
SuperClassRepositoryfindAll()
将搜索所有A和B类
我们设法在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
的适当映射器的存在,因此当findAll
(或其他方法)在ARepository
中调用时,每个子类的映射器都存在。完成此操作后,我们能够获得实际上是B
实例的A
列表。
希望这能有所帮助,没有人需要在这上面浪费更多的时间。:)