How to generate UUID in Clojure

Each object should have an unique identifier, in relational database, usually an incremental integer is used to each row in table. NoSQL database usually uses an UUID , for example MongoDB uses a 32-byte hexadecimal string to represent a UUID BSON subtype.

In Clojure, we usually use Java's java.util.UUID as a tool to generate UUID.

Let's see what inside this class

(defn show [ t ] 
  (map #(println %) (seq (:declaredMethods (bean t)))  
user=> (show java.util.UUID)
(#<Method public boolean java.util.UUID.equals(java.lang.Object)>
#<Method public java.lang.String java.util.UUID.toString()>
nil #<Method public int java.util.UUID.hashCode()>
nil #<Method public int java.util.UUID.compareTo(java.lang.Object)>
nil #<Method public int java.util.UUID.compareTo(java.util.UUID)>
nil #<Method public long java.util.UUID.timestamp()>
nil #<Method private static java.lang.String java.util.UUID.digits(long,int)>
nil #<Method public int java.util.UUID.version()>
nil #<Method public int java.util.UUID.variant()>
nil #<Method public long java.util.UUID.node()>
nil #<Method public int java.util.UUID.clockSequence()>
nil #<Method public static java.util.UUID java.util.UUID.fromString(java.lang.String)>
nil #<Method public long java.util.UUID.getLeastSignificantBits()>
nil #<Method public long java.util.UUID.getMostSignificantBits()>
nil #<Method public static java.util.UUID java.util.UUID.nameUUIDFromBytes(byte[])>
nil #<Method public static java.util.UUID java.util.UUID.randomUUID()>
nil nil)

We will use the static method randomUUID which will return a java.util.UUID instance

(defn uuid [] (.toString (java.util.UUID/randomUUID)))

We first create an java.util.UUID instance then call toString to get the string form.

Another way to get an unique id is by using the MongoDB id, which is used for every bson document in MongoDB, and they are shorter than the standard UUID. Get the dependency bson-3.0.2.jar.

The function will be

(defn mid []
  (print (.toString (org.bson.types.ObjectId.)))

The id looks like this

user> (mid)