1.实体类
import jakarta.persistence.*;
import lombok.Data;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.util.Date;
@Entity
@Table(name = "teacher")
@EntityListeners({AuditingEntityListener.class})
@Data
public class Teacher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@CreatedBy
private String createUserId;
@LastModifiedBy
private String updateUserId;
@CreatedDate
private Date createTime;
@LastModifiedDate
private Date updateTime;
}
2.审计配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import java.util.Optional;
@EnableJpaAuditing
@Configuration(proxyBeanMethods = false)
public class TeacherAuditor {
@Bean
public AuditorAware<String> auditorProvider() {
// TODO 获取当前主体 do something...
return () -> Optional.of("123456");
}
}
3.执行repository方法
import com.tiger.jpatest.entity.Teacher;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class TeacherDaoTest {
@Autowired
TeacherDao teacherDao;
@Test
void name() {
Teacher teacher1 = teacherDao.findById(2L).orElse(null);
teacher1.setName("asd");
teacherDao.save(teacher1);
}
}
4.第二种配置
public class CustomEntityAuditingListener {
@PrePersist
private void prePersist(BaseEntity entity) {
// 获取当前用户,具体获取逻辑请自行实现
SysUser current = new SysUser();
entity.setCreatorId(current.getId());
entity.setCreator(current.getUsername());
entity.setLastModifierId(current.getId());
entity.setLastModifier(current.getUsername());
}
@PreUpdate
private void preUpdate(BaseEntity entity) {
// 获取当前用户,具体获取逻辑请自行实现
SysUser current = new SysUser();
entity.setLastModifierId(current.getId());
entity.setLastModifier(current.getUsername());
}
}
@Getter
@Setter
@Entity
@EntityListeners({AuditingEntityListener.class, CustomEntityAuditingListener.class})
public class SysUser implements Serializable {
/**
* ID,唯一标识列,使用主键自增策略
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 创建时间
*/
@CreatedDate
private LocalDateTime createdTime;
/**
* 最后修改时间
*/
@LastModifiedDate
private LocalDateTime lastModifiedTime;
/**
* 创建人ID
*/
@CreatedBy
private Long creatorId;
/**
* 创建人用户名
*/
private String creator;
/**
* 最后修改人ID
*/
@LastModifiedBy
private Long lastModifierId;
/**
* 最后修改人用户名
*/
private Long lastModifier;
/**
* 用户名
*/
@Column(unique = true)
private String username;
/**
* 密码
*/
private String password;
/**
* 电话
*/
private String phone;
}