2

I want to use UUID instead of the plain String value for fields annotated with @Id, for example:

@Data // Lombok
public class Role {

    @Id
    private UUID id;

    @Size(max = 18)
    private String name;

}

However, inserting such object leads to Cannot autogenerate id of type java.util.UUID for entity of type Role exception.

For reference, I've tried the following custom configuration with no success:

@Configuration
public class DatabaseConfiguration extends AbstractReactiveMongoConfiguration {

    @Override
    protected String getDatabaseName() {
        return "test";
    }

    @Override
    public void configureClientSettings(MongoClientSettings.Builder builder) {
        builder.uuidRepresentation(UuidRepresentation.STANDARD); // <---
    }
    
}

Are there any approaches to make it work WITHOUT creating custom AbstractMongoEventListener per each model (creating one for the base class does not work either)?

Yves Calaci
  • 1,019
  • 1
  • 11
  • 37

1 Answers1

-1

Currently, generating IDs of data types other than ObjectId, String or BigInteger wasn't directly possible before Spring Data MongoDB 2.0, 1.10.1 and 1.9.8.

For more details see: https://craftingjava.com/blog/custom-document-id-spring-data-mongodb/

As an extra thought on the workaround with CustomMongoRepositoryImpl, you can create a custom aspect annotation as a universal mount point for all repositories, and within that aspect, you can have a mapping between client id types and generators.

saver
  • 2,541
  • 1
  • 9
  • 14
  • The proposed solution within that link uses `AbstractMongoEventListener`, which is against what I'm looking for (as stated in my post). – Yves Calaci Dec 31 '20 at 01:48
  • I meant to consider the solution with CustomMongoRepositoryImpl – saver Dec 31 '20 at 02:00
  • This solution is meant for older versions and is even worse than creating multiple `AbstractMongoEventListener` only. – Yves Calaci Dec 31 '20 at 02:56