This post was originally published on this site
Spring data has a feature that allows you to track automatically a certain amount of fields through annotations :
- @CreatedDate : The date on which the entity was created
- @CreatedBy : The user that created the entity
- @LastModifiedDate : The date the entity was last modified
- @LastModifiedBy : The user that modified last the entity
- @Version : the version of the entity (increased each time the entity is modified and savesd)
Let’s say for example we have this simple entity with the appropriate annotations :
@Entity
@EntityListeners(AuditingEntityListener.class)
public class Contact implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Version()
private Long version = 0L;
@NotNull
@CreatedDate
private Date creationDate;
@NotNull
@Size(max = 50)
@CreatedBy
private String creationUserLogin;
@NotNull
@LastModifiedDate
private Date modificationDate;
@NotNull
@Size(max = 50)
@LastModifiedBy
private String modificationUserLogin;
private String firstName;
private String lastName;
//GETTERS - SETTERS and other code
}
And we’re using the following service class and repository :
@Service
public class ContactServiceImpl implements ContactService{
@Autowired
private ContactRepository contactRepository;
public Contact save(Contact contact){
return contactRepository.save(entity);
}
}
public interface ContactRepository extends JpaRepository<Contact, Long> {
}
Now whenever you change the value of one of the fields in the entity; the fields marked with @Version, @LastModified and @LastModifiedBy will be updated with new values automatically.
Now recently I had the case where I had to “touch” an entity (like in linux) so that the version will be increased as well as @LastModified and @LastModifiedBy will be updated accordingly even though none of the fields had been updated
Now you cannot update the automatically handled fields manually, but there is a way you can achieve this by using Spring’s AuditingHandler; so we could modify our service class as follows :
@Service
public class ContactServiceImpl implements ContactService{
@Autowired
private ContactRepository contactRepository;
@Autowired
private AuditingHandler auditingHandler;
public Contact save(Contact contact, boolean forceVersionIncrease){
//force version update even though no values have changed in the entity
if(forceVersionIncrease){
auditingHandler.markModified(contact);
}
return contactRepository.save(entity);
}
}
And there you go, you should be able now to “touch” your entities and force date and version updates