简体   繁体   中英

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

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM