Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How work with immutable object in mongodb and lombook without @BsonDiscriminator

I tried to work with immutable objects in MongoDB and Lombok. I found a solution to my problem but it needs to write additional code from docs but I need to used Bson annotations and create a constructor where describes fields via annotations. But if I user @AllArgsConstructor catch exception: "Cannot find a public constructor for 'User'" because I can't use default constructor with final fields. I think i can customize CodecRegistry correctly and the example will work correctly but I couldn't find solution for it in docs and google and Stackoverflow.

Is there a way to solve this problem?

@Data
@Builder(builderClassName = "Builder")
@Value
@BsonDiscriminator
public class User {
    private final ObjectId id;
    private final String name;
    private final String pass;
    private final String login;
    private final Role role;

    @BsonCreator
    public User(@BsonProperty("id") final ObjectId id,
                @BsonProperty("name") final String name,
                @BsonProperty("pass") final String pass,
                @BsonProperty("login") final String login,
                @BsonProperty("role") final Role role) {
        this.id = id;
        this.name = name;
        this.pass = pass;
        this.login = login;
        this.role = role;
    }

    @AllArgsConstructor
    public enum Role {
        USER("USER"),
        ADMIN("ADMIN"),
        GUEST("GUEST");

        @Getter
        private String value;
    }

    public static class Builder {

    }

}

Example for MongoDB where I create, save and then update users:

public class ExampleMongoDB {


    public static void main(String[] args) {
        final MongoClient mongoClient = MongoClients.create();
        final MongoDatabase database = mongoClient.getDatabase("db");
        database.drop();
        final CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
            fromProviders(PojoCodecProvider.builder().automatic(true).build()));
        final MongoCollection<User> users = database.getCollection("users", User.class).withCodecRegistry(pojoCodecRegistry);
        users.insertMany(new ExampleMongoDB().getRandomUsers());
        System.out.println("Before updating:");
        users.find(new Document("role", "ADMIN")).iterator().forEachRemaining(
            System.out::println
        );
        System.out.println("After updating:");
        users.updateMany(eq("role", "ADMIN"), set("role", "GUEST"));
        users.find(new Document("role", "GUEST")).iterator().forEachRemaining(
            System.out::println
        );
    }


    public List<User> getRandomUsers() {
        final ArrayList<User> users = new ArrayList<>();
        for (int i = 0; i < 15; i++) {
            users.add(
                User.builder()
                    .login("log" + i)
                    .name("name" + i)
                    .pass("pass" + i)
                    .role(
                        (i % 2 == 0) ? User.Role.ADMIN : User.Role.USER
                    ).build()
            );
        }
        return users;
    }

}
like image 367
kejam Avatar asked Sep 19 '25 21:09

kejam


1 Answers

This should work (it worked for me):

@Builder(builderClassName = "Builder")
@Value
@AllArgsConstructor(onConstructor = @__(@BsonCreator))
@BsonDiscriminator
public class User {
   @BsonId
   private final ObjectId _id;

   @BsonProperty("name")
   private final String name;

   @BsonProperty("pass")
   private final String pass;

   @BsonProperty("login")
   private final String login;

   @BsonProperty("role")
   private final Role role;
}

Then in lombok.config add these (in your module/project directory):

lombok.addLombokGeneratedAnnotation=true
lombok.anyConstructor.addConstructorProperties=true
lombok.copyableAnnotations += org.bson.codecs.pojo.annotations.BsonProperty
lombok.copyableAnnotations += org.bson.codecs.pojo.annotations.BsonId

Also piece of advice, keep _id if you are going to use automatic conversion to POJOs using PojoCodec, which will save a lot of trouble.

like image 188
saganas Avatar answered Sep 22 '25 11:09

saganas