【问题标题】:get dbref from document in Mongo using Java使用 Java 从 Mongo 中的文档中获取 dbref
【发布时间】:2013-02-21 16:30:00
【问题描述】:

我无法从 Mongo 获取 dbRef 对象。在我的实体包中,我有一个 User 类继承了 Parent 类。 这是User 类:

public class User {

@Id
private ObjectId id;

@DBRef
private Account account;

private String name;

public String getId() {
    if (id != null) {
        return id.toStringMongod();
    }           

    return null;//no id
}

public void setId(ObjectId objectId) {
    this.id = objectId;
}

public Account getAccount() {
    return account;
}

public void setAccount(Account account) {
    this.account = account;
}
public String getLogin() {
    return login;
}

public void setLogin(String login) {
    this.login = login;
}
}

正如你在上面看到的,我在这里放了一个Account 的对象。 我的Parent 类只是扩展了User

@Document
public class Parent extends User {

@JsonProperty("is_activated")
private boolean isActivated;

public boolean isActivated() {
    return isActivated;
}

public void setActivated(boolean isActivated) {
    this.isActivated = isActivated;
}
}

注意:isActivated 没有什么神奇之处。

在我的ParentDaoImpl 班级:

@Service
public class ParentDaoImpl extends AbstractDaoImpl implements ParentDao {

@Override
public Parent getParentByLogin(String login) {
    Query query = new Query(Criteria.where("login").is(login));
    return mongoOperations.findOne(query, Parent.class, "parents");
}
}

问题是如果我调用getParentByLogin 方法,它会返回evertyning 但Account 字段为空。也许findOne 里面没有给出 dbRef。我认为在关系数据库中,会有类似join 的东西。我希望我的方法也给我account 字段。

感谢您的帮助!

【问题讨论】:

  • 您实际上在帐户字段中设置了什么?如果它返回null,我猜它是……null。不确定 mongodb java 驱动程序是否会自动解析 dbref。也许你需要添加一些 Annotation(配置)来自动加载 dbrefs。
  • 我没有提到Account 类。提供在getParentBylogin 之前创建帐户。我的意思是我首先为父母创建了帐户(我可以在 mongo shell 或通过我的应用程序中获得它),然后尝试获得整个父母
  • 你是使用纯mongodb java驱动还是围绕它的一些框架,比如Spring Data/morphia? @Service 看起来像 Spring Data。也许您应该首先举一个简短的示例来填充数据库。也许有错误。
  • 我正在使用 Spring。在我在这里发布之前,我实际上很小心地测试了它。不幸的是,现在我成功了。我为此道歉!无论如何,谢谢。

标签: java mongodb dbref


【解决方案1】:

你能试试这样的吗?

....
@Field("fieldName")
@DBRef(collection = "mongoCollectionName")
private Account account;
....

【讨论】:

  • 感谢您的回复。我试过了,没有成功。仍然返回 null,即使存在与父对象相关的特定帐户
  • 我第一次尝试在您的回复的帮助下似乎失败了。但最近,我做到了。非常感谢!
  • 当我添加 @DBRef(collection = "mongoCollectionName") 时,它说没有名为 collection 的方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-12
  • 1970-01-01
  • 1970-01-01
  • 2017-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多