0

I am using immutables to interact with MongoDB. I am creating a very simple example below:-

@Mongo.Repository
@Value.Immutable
@Gson.TypeAdapters
@JsonDeserialize(as = ImmutablePerson.class)
@JsonSerialize(as = ImmutablePerson.class)
public interface Person {

    @Mongo.Id
    @Value.Auxiliary
    int id();

    String name();
}

When I create an object by

ImmutablePerson.builder().name("Amar").build();

I get an exception, which is the following:-

Cannot build Person, some of required attributes are not set [id]
    at com.model.ImmutablePerson$Builder.build(ImmutablePerson.java:247) ~[classes/:na]
    at com.Main.run(Main.java:56) [classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732)

I have also tried the following, but it also does not work.

@Mongo.Repository
@Value.Immutable
@Gson.TypeAdapters
@JsonDeserialize(as = ImmutablePerson.class)
@JsonSerialize(as = ImmutablePerson.class)
public abstract class Person {

    @Mongo.Id
    @Value.Auxiliary
    public abstract int id();

    public abstract String name();
}

What am I doing wrong here ??

Thanks,

Amar

Amar Dev
  • 1,360
  • 2
  • 18
  • 38

1 Answers1

1

This is because your id() isn't set while trying to build the object.

Either manage your own id generation (probably via AtomicInteger.incrementAndGet()) or let it manage by Immutable library

  @Mongo.Id
  @Value.Default
  public Id id() {
    return Id.generate();
  }
FrostNova
  • 51
  • 4