我有一个实体借用,现在我想在使用BorrowingEntityListeners向表BorrowingHistory中添加新记录时备份借用, 问题在于,侦听器应使用存储库将信息保存到数据库中,这意味着实体Borrowing和BorrowingHistory应该依赖于Repository模块。 但是模块Repository已经取决于Model模块了,不是吗? 这是一个交叉依赖问题。
您知道如何解决吗?
我应该将模型和存储库合并为一个模块吗?
public enum Action {
INSERTED("INSERTED"),
UPDATED("UPDATED"),
DELETED("DELETED");
private final String name;
private Action(String value) {
this.name = value;
}
public String value() {
return this.name;
}
@Override
public String toString() {
return name;
}
}
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable<U> {
@CreatedBy
protected U createdBy;
@CreatedDate
protected LocalDateTime createdDateTime;
@LastModifiedBy
protected U lastModifiedBy;
@LastModifiedDate
protected LocalDateTime lastModifiedDateTime;
}
@Service
public class BeanUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext
applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
}
public class BorrowingEntityListener {
@PostPersist
public void prePersist(Borrowing target) {
perform(target, Action.INSERTED);
}
@PreUpdate
public void preUpdate(Borrowing target) {
perform(target, Action.UPDATED);
}
@PreRemove
public void preRemove(Borrowing target) {
perform(target, Action.DELETED);
}
@Transactional(MANDATORY)
void perform(Borrowing target, Action action) {
BorrowingHistoryRepository borrowingHistoryRepository = BeanUtil.getBean(BorrowingHistoryRepository.class);
borrowingHistoryRepository.save(new BorrowingHistory(target, action));
}
}
@Entity
@EntityListeners(BorrowingEntityListener.class)
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@Getter @Setter
public class Borrowing extends Auditable<String> {
...
}
@Entity
@EntityListeners(BorrowingEntityListener.class)
public class BorrowingHistory {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne
@JoinColumn(name = "borrowing_id", foreignKey = @ForeignKey(name = "FK_borrowing_history_borrowing"))
private Borrowing borrowing;
private String borrowingContent;
@CreatedBy
private String modifiedBy;
@CreatedDate
private LocalDateTime modifiedDateTime;
@Enumerated(STRING)
private Action action;
}