Radislav
Radislav

Reputation: 2983

How to use .net GUID in JAVA UUID as primary key of mongodb collection

I have mongodb database where each document in each collection has _id field which is .net GUID. Now we want to work with the same data base from java application. How to convert GUID to UUID and map objects correctly?

Upvotes: 0

Views: 674

Answers (2)

Radislav
Radislav

Reputation: 2983

I have found solution. Hope it will help someone else. So I took the code of util js file for CSUUID convertion to UUID in robomongo and rewrite it to JAVA.

private String HexToBase64(String hex) {
        char[] base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
        String base64 = "";
        int group;     
        for (int i = 0; i < 30; i += 6) {
            group = Integer.parseInt(mySubString(hex, i, 6), 16);
            base64 += base64Digits[(group >> 18) & 0x3f];
            base64 += base64Digits[(group >> 12) & 0x3f];
            base64 += base64Digits[(group >> 6) & 0x3f];
            base64 += base64Digits[group & 0x3f];
        }
        group = Integer.parseInt(mySubString(hex, 30, 2), 16);
        base64 += base64Digits[(group >> 2) & 0x3f];
        base64 += base64Digits[(group << 4) & 0x3f];
        base64 += "==";
        return base64;
    }
    private String mySubString(String myString, int start, int length) {
        return myString.substring(start, Math.min(start + length, myString.length()));
    }
    private String CSUUID(String csuuid) {
        String hex = csuuid.replaceAll("[{}-]", ""); // remove extra characters
        String a = mySubString(hex, 6, 2) + mySubString(hex, 4, 2) + mySubString(hex, 2, 2) + mySubString(hex, 0, 2);
        String b = mySubString(hex, 10, 2) + mySubString(hex, 8, 2);
        String c = mySubString(hex, 14, 2) + mySubString(hex, 12, 2);
        String d = mySubString(hex, 16, 16);
        hex = a + b + c + d;
        String base64 = HexToBase64(hex);               
        //return base64.getBytes(StandardCharsets.UTF_8);
        return base64;
    }

Now to perform query by CSUUID need to perform such query:

var user = _mongo.findOne(Query.query(Criteria.where("_id").is(new Binary(Bytes.B_UUID, Base64.getDecoder().decode(CSUUID(id.toString()))))), User.class);  

Thanks!

Upvotes: 0

Jens
Jens

Reputation: 590

A Java UUID and a Mongodb UUID both implement the UUID standard.

The textual representation can be parsed with e.g. fromString:

UUID myUUID = UUID.fromString("449772DE-2780-4412-B9F7-E49E48605875");

To convert a UUID into the String representation use toString:

String uuid = myUUID.toString(); 
// gives "449772de-2780-4412-b9f7-e49e48605875"

Upper-/lowercase does not matter (as can be seen in this example).

See the quickstart on how to query for documents.

Upvotes: 1

Related Questions