MongoDB/Morphia将技术ID保存为ObjectId,尽管它是Java中的String [英] MongoDB / Morphia saves technical id as ObjectId although it's a String in Java

查看:99
本文介绍了MongoDB/Morphia将技术ID保存为ObjectId,尽管它是Java中的String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MongoDB中有两种文档:客户端和代码.每个代码都引用一个客户端.客户端必须由管理员显式存储,因此我必须将它们分开存储,并且不能将它们放入代码文档中.

I've got two kinds of documents in my MongoDB: clients and codes. Each code refers to one client. Clients have to be stored explicitly by an administrator, therefore I have to store them separate and cannot put them into a code document.

code -> client

现在,MongoDB/Morphia将客户端的技术ID保存为ObjectId,而代码引用的技术ID为String的客户端.我可以通过给定的客户端ID搜索代码,但是在运行时我会收到一条错误消息,因为Morphia无法注入客户端.我认为是因为ID类型不同.

Now MongoDB / Morphia saves technical ids of clients as ObjectId, whereas codes refer to clients with a technical id of type String. I am able to search a code by a given client id, but at the runtime I'll get a error message, because Morphia cannot inject the client. I assume it's because of the different id types.

code { client.$id: String }
client { _id: ObjectId }

有什么办法解决这个问题吗?

Any ideas how to fix this?

例外

com.google.code.morphia.mapping.MappingException:无法为org.example.Code.client获取参考({"$ ref":"clients","$ id":"123456789abcdef"})

com.google.code.morphia.mapping.MappingException: The reference({ "$ref" : "clients", "$id" : "123456789abcdef" }) could not be fetched for org.example.Code.client

在互联网上,我发现了该异常消息.建议在模型中使用ObjectId代替String,但是我有使用String的要求.这不是我自己的项目.

On the internet I found that exception message. It was suggested to use ObjectId instead of String in the model, but I have the requirement to use String. This is not my own project.

实体:

@Entity("codes")
public class Code implements Comparable<Code> {
    @Id
    private String id;

    @Reference
    private Client client;

    [...]
}

@Entity("clients")
public class Client {
    @Id
    private String id;
}

存储:

要存储对象,请使用com.google.code.morphia.dao.DAO.save(T entity).

搜索:

public class CodeRepository extends BasicDAO<Code, String> {
    [... constructor ...]

    @Override
    public Code findByCode(String type, String clientId, String code) {
        return findOne(createQuery()
                .field("type")
                .equal(type)
                .field("value")
                .equal(code)
                .field("client")
                .equal(new Key<Client>(Client.class, clientId)));
    }
}

推荐答案

不确定是否已解决.我有同样的问题.对我来说,解决方案是自己设置ID.

not sure if this is solved yet. I had the same problem. The solution for me was to set the id myself.

@Id
private String id = new ObjectId().toString();

现在,您可以将id字段与其他任何字符串字段一样对待.

Now you can treat the id field like any other string field.

希望这会有所帮助.

这篇关于MongoDB/Morphia将技术ID保存为ObjectId,尽管它是Java中的String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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