javamongodbuniqueidentifierauto-generateimmutables-library

How to autogenerate a Unique ID from Immutables Criteria Library?


The advice given on Immutables site is to switch to the new Immutables-Criteria functionality. In this sense I try to convert my project so that instead of Immutables-MongoDB it uses the Immutables-Criteria .

Immutables-MongoDB provides the Id.generate() method as a Default way to auto-generate unique id for an object. There is an example here.

import org.immutables.value.Value;
import org.immutables.mongo.types.Id;

@Value.Immutable 
public abstract class ExampleMongoID{   

      // Autogenerating a id and converting it to a String
      // This is a slightly modified and simplifed version of the [example of the site][3].
      @Mongo.Id   
      @Value.Default   
      public String id() {
        return Id.generate().toString();   
     }

}

However the equivalent tag does not have any method similar or equivalent to the generate() method. Neither such a method related to ID could be found in the criteria API.

In the project that needs to be converted Id.generate() is used prior to inserting/coming. Is there any way I can achieve the effect of calling Id.generate() from the new Immutables-Criteria API? I would prefer to know what is the preferred Immutables-Criteria based way. One solution could be to auto-generate a GUID but I would like to use the recommended approach (if there is one) so I can be more compatible with future updates.


Solution

  • Coming back to this question, I have been using this approach for quite some time and seems to work well.

    @Value.Immutable 
    public abstract class ExampleMongoID{   
    
      @Criteria.Id
      @Value.Default
      public String getId() {
         return java.util.UUID.randomUUID().toString();
      }
    
    }