В Spring Boot есть стартер JaVers:
Код: Выделить всё
implementation("org.javers:javers-spring-boot-starter-sql:7.5.0")
Код: Выделить всё
import javax.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
@Entity
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List departments;
}
@Getter
@Setter
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List employees;
}
@Getter
@Setter
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
Код: Выделить всё
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.javers.spring.annotation.JaversSpringDataAuditable;
@Repository
@JaversSpringDataAuditable
public interface CompanyRepository extends JpaRepository {}
@Repository
@JaversSpringDataAuditable
public interface DepartmentRepository extends JpaRepository {}
@Repository
@JaversSpringDataAuditable
public interface EmployeeRepository extends JpaRepository {}
Код: Выделить всё
import org.javers.core.Javers;
import org.javers.repository.jql.QueryBuilder;
import org.javers.repository.jql.JqlQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CompanyAuditService {
private final Javers javers;
private final CompanyRepository companyRepository;
@Autowired
public CompanyAuditService(Javers javers, CompanyRepository companyRepository) {
this.javers = javers;
this.companyRepository = companyRepository;
}
public String getCompanyChangesJson(Long companyId) {
Company company = companyRepository.findById(companyId)
.orElseThrow(() -> new RuntimeException("Company not found"));
JqlQuery javersQuery = QueryBuilder.byInstance(company).withScopeDeepPlus().build();
List changes = javers.findChanges(javersQuery);
return javers.getJsonConverter().toJson(changes);
}
}
Код: Выделить всё
Employee employee = new Employee();
employee.setName("John Doe");
Department department = new Department();
department.setEmployees(List.of(employee));
Company company = new Company();
company.setDepartments(List.of(department));
companyRepository.save(company);
// Update the employee's name
employee.setName("Johnathan Doe");
employeeRepository.save(employee);
// Fetch and print changes for the company
String changesJson = companyAuditService.getCompanyChangesJson(company.getId());
System.out.println("Company changes, should contain: Johnathan changes" + changesJson);
Подробнее здесь: https://stackoverflow.com/questions/787 ... nvironment
Мобильная версия