What is the use of @PersistenceCreator annotation

2.1k Views Asked by At

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;
    }
}
1

There are 1 best solutions below

4
KHALEF Ahmed On BEST ANSWER

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