使用Spring Data和MongoDB解析子文档类型 [英] Resolving subdocument types with Spring Data and MongoDB

查看:552
本文介绍了使用Spring Data和MongoDB解析子文档类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试解析属性表达式时遇到Spring Data存储库的错误:

I'm encountering an error with a Spring Data repository as it attempts to resolve a property expression:

public interface ContractRepository
    extends MongoRepository<Contract,String> {
    public List<Contract> findByCodeBindings(String binding);
}

以下是合约的相关部分

@Document(collection="CONTRACTS")
public class PersistentContract extends BaseContract {
    @PersistenceConstructor
    public PersistentContract(String name, Version version, Code code) {
        super(name, version, code);
    }
}

代码是由 CodeImpl 实现的接口。它包含一个属性 bindings ,它在代码中有一个getter和setter。因此,查询的属性表达式旨在使用包含给定绑定的嵌套代码文档来查找这些契约。到目前为止,非常好。

Code is an interface implemented by CodeImpl. It contains a property bindings, which has a getter and setter in Code. So the query's property expression is designed to find those contracts with a nested Code document containing a given binding. So far, so good.

然而,问题是 IllegalArgumentException 被抛出:

java.lang.IllegalArgumentException: No property bindings found on my.company.Code!
 org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:225)

调试该部分代码显示Spring Data正在分离表达式并确定存在类型为 Code 的属性。但是,因为代码是一个接口,所以它没有列出属性。

Debugging that section of code shows that Spring Data is picking apart the expression and determines there's a property of type Code. However, because Code is an interface, it has no properties listed.

有没有办法提示Spring 代码的数据具有此属性或 CodeImpl 代码<的实际类型/ code>财产?我很惊讶该库不会尝试解析接口的getter或setter。

Is there a means to hint to Spring Data that either Code has this property or that CodeImpl is the actual type of the code property? I'm surprised that the library doesn't attempt to parse the getters or setters of the interface.

这是使用spring-data-commons 1.5.1.RELEASE和spring-data-mongodb 1.2.1.RELEASE。

This is using spring-data-commons 1.5.1.RELEASE and spring-data-mongodb 1.2.1.RELEASE.

感谢帮助。

推荐答案

我的解决方案是避免持久对象中的接口。所以 BaseContract 变成了以下内容:

My solution was to avoid interfaces at all in the persistent object. So BaseContract became the following:

public abstract class BaseContract<T extends Code> {
    public abstract T getCode();
}

PersistentContract 是根据具体类实现:

public class PersistentContract extends BaseContract<CodeImpl> {
}

这似乎在对基类中的接口进行编码之间取得了适当的平衡并满足Spring Data对具体课程的需求。

This seems to strike the right balance between coding against interfaces in the base class and satisfying Spring Data's need for concrete classes.

这篇关于使用Spring Data和MongoDB解析子文档类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆