【发布时间】:2018-09-21 09:37:34
【问题描述】:
我的审计监听器
public class EmployeeAuditListeners {
@PrePersist
public void prePersist(Employee employee){
perform(employee,Action.INSERTED);
}
@PreUpdate
public void preUpdate(Employee employee){
perform(employee,Action.UPDATED);
}
@PreRemove
public void preRemove(Employee employee){
perform(employee,Action.DELETED);
}
@Transactional
public void perform(Employee emp, Action action){
EntityManager em = BeanUtil.getBean(EntityManager.class);
CommonLogs commonLogs = new CommonLogs();
commonLogs.setQuery("new query");
em.persist(commonLogs);
}
}
和我的Auditable.class
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable<U> {
@CreatedBy
protected U createdBy;
@CreatedDate
@Temporal(TemporalType.TIMESTAMP)
protected Date createdDate;
@LastModifiedBy
protected U lastModifiedBy;
@LastModifiedDate
@Temporal(TemporalType.TIMESTAMP)
protected Date lastModifiedDate;
}
我的CommonLogs.class
@Entity
@EntityListeners(AuditingEntityListener.class)
public class CommonLogs extends Auditable<String> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String query;
public CommonLogs() {
}
public CommonLogs(String query) {
this.query = query;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
}
我的 Employee.java 类
@Entity
@EntityListeners(EmployeeAuditListeners.class)
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String address;
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;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
我有一个简单的 Rest Controller
@RestController
@RequestMapping("/api")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@PostMapping("/employees")
public Employee createEmployee(@RequestBody Employee employee){
return employeeRepository.save(employee);
}
}
每次我对我的 Employee Entity 执行一些 crud 操作时,我都想将它记录在我的表 (common_logs) 上。
上面给出的示例在某种程度上是有效的,因为它成功地存储了员工并调用了 EmployeeAuditListeners。
但现在在保存 CommongLog 实体时,我希望它的父类 Auditable 可以自动插入 createdBy、createdDate 等。现在只有查询和 id 被插入到 common_logs 表中,其余列为空。
【问题讨论】:
标签: spring-boot spring-data-jpa