i currently have this issue while working on a Spring Boot project. i have a project entity that have this fields (CreatedBy and setLastModifiedBy), using the MongoDB EnableMongoAuditing annotation i was able to populate the Date fields. These two fields will reference the user that either created or modified the entity. currently i have the following implementation:
public Project create(Project project) {
User user = userRepository.findByUsername(SecurityContextHolder.getContext().getAuthentication().getName()).orElseThrow(() -> new UserNotFoundException());
getByName(project.getName()).ifPresent(existing -> {
throw new ProjectAlreadyExistsException(existing.getName());
});
// refactor
project.setActive(true);
project.setCreatedBy(user.getId());
project.setLastModifiedBy(user.getId());
return projectRepository.save(project);
}
As you can see the fields are set manually inside the service, which seems a bit odd and not like a good practice for me.
can this be done in another way?