i am currently adding Auditing to my Entities. That is working fine but i want to save the Id of the User which is related to the Entity inside the @CreatedBy and @LastModifiedBy Columns and not the Name which i have right now.
I am also using Spring Security + JWT to get the User which is working fine.
How can i achieve this with the following Configuration?
User Entity:
@Entity(name = "User")
@Table(name = "user")
public class User extends Auditable<String> {
@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "UserSequence")
@GenericGenerator(
name = "UserSequence",
strategy = "com.simagdo.crmAPI.utils.SequenceIdGenerator",
parameters = {
@org.hibernate.annotations.Parameter(name = SequenceIdGenerator.INCREMENT_PARAM, value = "1"),
@org.hibernate.annotations.Parameter(name = SequenceIdGenerator.VALUE_PREFIX_PARAMETER, value = "130"),
@org.hibernate.annotations.Parameter(name = SequenceIdGenerator.NUMBER_FORMAT_PARAMETER, value = "%05d")
}
)
@Column(name = "Id")
private String id;
@Column(
name = "UserName",
length = 80,
unique = true)
private String userName;
@Column(name = "Password")
private String password;
}
AuditorAware:
public class AuditAwareImpl implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.of("Simagdo");
}
}
The config:
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class JpaConfig {
@Bean
public AuditorAware<String> auditorAware() {
return new AuditAwareImpl();
}
}
My Auditable Class:
@MappedSuperclass
public abstract class Auditable<U> {
@CreatedBy
@OneToOne(
orphanRemoval = true,
cascade = {
CascadeType.PERSIST,
CascadeType.REMOVE
}
)
private User createdBy;
@CreatedDate
@Column(
name = "CreatedDate",
nullable = false,
updatable = false
)
private LocalDateTime createdDate;
@LastModifiedBy
@OneToOne(
orphanRemoval = true,
cascade = {
CascadeType.PERSIST,
CascadeType.REMOVE
}
)
private User lastModifiedBy;
@LastModifiedDate
@Column(
name = "LastModifiedDate",
nullable = false
)
private LocalDateTime lastModifiedDate;
}