Search code examples
javaspringmongodbspring-data-mongodbmongorepository

What is the use of @PersistenceCreator annotation


I have a User.java class that is Model of User collection. I want to make a few fields in it as private final but when I am doing so , it shows error "final fields may not have been initialised" but Since I am expecting the fields to be initialised by UserRepository I can't initialise the fields at time of declaration.


I tried creating a constructor with all the fields and it works(with out using @PersistenceCreator), then there also a @PersistenceCreator annotation whose use I don't know , according to documentation it declares the annotated constructor as default one but there is no further explanation. Note that the constructor works with or without annotation.


Please explain : What is the use of @PersistenceCreator annotation.

@Document
public class User {
    @Id
    private final int id;
    @Field("user_name")
    private final String userName;
    private final String password;
    private final boolean active;
    private final String roles;
    @Field("from_phone_number_id")
    private final String fromPhoneNumberId;
    @Field("access_token")
    private final String accessToken;

    
    @PersistenceCreator
    public User(int id, String userName, String password, boolean active, String roles, String fromPhoneNumberId,
            String accessToken) {
        this.id = id;
        this.userName = userName;
        this.password = password;
        this.active = active;
        this.roles = roles;
        this.fromPhoneNumberId = fromPhoneNumberId;
        this.accessToken = accessToken;
    }
}

Solution

  • Spring Data automatically tries to detect a persistent entity’s constructor to be used to materialize objects of that type, if there is a single static factory method annotated with @PersistenceCreator then it is used.

    Here's the documentation which describes it in more detail:

    Spring Data automatically tries to detect a persistent entity’s constructor to be used to materialize objects of that type. The resolution algorithm works as follows:

    1. If there is a single static factory method annotated with @PersistenceCreator then it is used.

    2. If there is a single constructor, it is used.

    3. If there are multiple constructors and exactly one is annotated with @PersistenceCreator, it is used.

    4. If the type is a Java Record the canonical constructor is used.

    5. If there’s a no-argument constructor, it is used. Other constructors will be ignored.