MongoDB / Morphia saves technical id as ObjectId although it's a String in Java

痞子三分冷 提交于 2019-12-07 11:45:28

问题


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

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?

Exception

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

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.

Entities:

@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;
}

Storing:

To store the objects I use com.google.code.morphia.dao.DAO.save(T entity).

Search:

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)));
    }
}

回答1:


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();

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

Hope this helps.




回答2:


I did it slightly differently so i could use the id as path param in REST requests.

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


来源:https://stackoverflow.com/questions/10444786/mongodb-morphia-saves-technical-id-as-objectid-although-its-a-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!