'Integrate Javers auto audit to JPA/Hibernate entitymanager without spring framework (Vanilla Javers)
I am currently working on a Java project with a REST service to store data which run with jarkarta, hibernate on a wildfly application server with a mysql db. To store the data I prepare a resource that a DAO to persist entities:
Service:
@Path("/users")
public class UserService extends BasicWebServiceOperation {
@Inject
private UserDao repo;
@POST
@Produces("application/json")
@UserRoles(values = {UserRole.ADMIN})
public Response createOrUpdateUser(UserDTO dto) {
ModelMapper modelMapper = new ModelMapper();
User newusr = modelMapper.map(dto, User.class);
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<User>> constraintViolations = validator.validate(newusr);
if (!constraintViolations.isEmpty()) {
response.setResponseToError(newusr, "INVALID_USER", "User with constraint violations");
}
try {
repo.persist(newusr);
} catch (PersistenceException e) {
response.setResponseToError(newusr, "Error", "Could not update or create user");
}
return createAndSendResponse();
}
}
DAO:
public abstract class BasicDao<T> {
@PersistenceContext
protected EntityManager em;
protected Class<T> inferredClass;
public BasicDao() {
}
public BasicDao(Class<T> inferredClass) {
this.inferredClass = inferredClass;
}
@JaversAuditable
public void persist(T entity) {
if(em.contains(entity)) {
em.merge(entity);
} else {
em.persist(entity);
}
}
@JaversAuditable
public void delete(T entity) {
em.remove(entity);
}
}
So far saving data works. Now i would like to audit every change why i decided me for javers. I have seen the auto-audit aspects which would be perfect for my dao so i set the @JaversAuditable because i dont use any spring framework libraries.
So far I have tried to create a simple class that initializes javers. However I don't know how this is then automatically registered. The only way left ist, that after the .persist() i just calling javers.commit but not looks nice. Are there any ways how i can solve it?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
