Hibernate JPA @GeneratorType Exaple
@GeneratorType
The @GeneratorType annotation is used to provide a ValueGenerator and a GenerationTime for the currently annotated generated attribute.GeneratorType Marks a property as generated, specifying the ValueGenerator type to be used for generating the value. It is the responsibility of the client to ensure that a generator type is specified which matches the data type of the annotated property.
Example : @GeneratorType mapping example
public static class CurrentUser {public static final CurrentUser INSTANCE = new CurrentUser();
private static final ThreadLocal<String> storage = new ThreadLocal<>();
public void logIn(String user) {
storage.set( user );
}
public void logOut() {
storage.remove();
}
public String get() {
return storage.get();
}
}
public static class LoggedUserGenerator implements ValueGenerator<String> {
@Override
public String generateValue(
Session session, Object owner) {
return CurrentUser.INSTANCE.get();
}
}
@Entity(name = "Person")
public static class Person {
@Id
private Long id;
private String firstName;
private String lastName;
@GeneratorType( type = LoggedUserGenerator.class, when = GenerationTime.INSERT)
private String createdBy;
@GeneratorType( type = LoggedUserGenerator.class, when = GenerationTime.ALWAYS)
private String updatedBy;
}
When the Person entity is persisted, Hibernate is going to populate the createdBy column with the currently logged user.
Comments
Post a Comment