Springboot hibernate envers使用过程详解

2020-06-22 13:04 来源:易采站长站 作者:丽君 点击: 评论:

A-A+

原标题:Springboot hibernate envers使用过程详解

添加maven配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.5.RELEASE</version>
  </parent>
  <artifactId>springboot-envers</artifactId>
  <name>springboot-envers</name>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-envers</artifactId>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>
  </dependencies>

</project>

使用User类作为被审计的对象

@Entity
@Table(name = "user")
@Audited
@JsonIgnoreProperties(value = "hibernateLazyInitializer")
public class User {

  @Id
  @GeneratedValue
  private Long id;
  private String name;

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

添加配置

spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.org.hibernate.envers.audit_strategy=org.hibernate.envers.strategy.internal.ValidityAuditStrategy
spring.jpa.properties.org.hibernate.envers.audit_strategy_validity_store_revend_timestamp=true
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:mem:envers
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driverClassName=org.h2.Driver

创建相应的UserRepository

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

添加用于增删改的Controller

@Controller
public class UserController {
  @Autowired
  private UserRepository userRepository;
  private int counter;

  @ResponseBody
  @RequestMapping("/user/add")
  public Object add() {
    User user = new User();
    user.setName("name" + ++counter);
    userRepository.save(user);
    return user;
  }

  @ResponseBody
  @RequestMapping("/user/update/{id}")
  public Object update(@PathVariable Long id) {
    User user = userRepository.getOne(id);
    user.setName("name" + ++counter);
    userRepository.save(user);
    return user;
  }
  @ResponseBody
  @RequestMapping("/user/delete/{id}")
  public Object delete(@PathVariable Long id) {
    User user = userRepository.getOne(id);
    userRepository.delete(user);
    return user;
  }
}

【易采站长站编辑:秋军】