I'm using SpringBoot with JPA/Hibernate and I'd like to add auditing.
I have created an abstract entity with the following :
@CreatedDate
@NotNull
@Column(columnDefinition = "DATETIME(3)", updatable = false)
private ZonedDateTime createdDate;
@LastModifiedDate
@Column(columnDefinition = "DATETIME(3)")
private ZonedDateTime lastModifiedDate;
The application
I'm developping a RESTful API with a simple CRUD on entities. My resources(controller) are using the save() method on jpa repositories for create and update
The problem :
When I'm calling repository.save() on an Entity to update it, the "createdDate" is ignored (that's normal) but the entity which is returned by the method has its"createdDate" set to null.
Then the entity is put in the cache and the next get will have its createdDate value to null also.
How can I update an entity without allowing the modification of the field createdDate and using JpaCrudRepository ?
Update
Repository definition :
public interface ModelRepository extends JpaRepository<Model, Long> {
REST Controller :
public ResponseEntity<Model> createModel(@RequestBody Model model) throws URISyntaxException {
Model result = modelRepository.save(model);
return ResponseEntity.created(new URI("/api/v1/models/" + result.getId()))
.body(result);
}
The Json returned by the endpoint contains "createdDate: null"
Update 2
To fix this issue I have created a service like this :
@Override
public Model save(Model model) {
Model result = modelRepository.save(model);
return result;
}
@Override
public Model update(Long id, Model model) {
Model existingModel = modelRepository.findOne(id);
if (existingModel == null) {
return null;
}
// Non updatable fields
model.setId(id);
model.setCreatedDate(existingModel.getCreatedDate());
Model result = modelRepository.save(model);
return result;
}
To make this work, i have also removed the "updatable = false" from createdDate field to prevent the result from having a null date after the save.
I don't understand the purpose of having "updatable = false" if we have to handle it manually after.