下面的代码是默认生成的Spring Roo,EntityManager在您的域模型POJO中注入其余方法来管理实体(save,update,delete,findXXX, ...)。Spring Roo:使用JPA实体作为DAO
也许它是一个更面向对象的方法(在对比的是anemic domain model),但我不明白的是:
有EntityManager的时候在每一个被注入任何性能问题(假设你从数据库中检索1000个实体)
不应该是事务管理(@Transactional注释)进入服务层吗? (想象一下,你想以原子的方式使用两个不同的实体)。
您可以考虑一下经典DAO层的这段代码的其他优点/缺点吗?
的代码看起来像这样(为清楚起见移除了一些方法):
@Configurable
@Entity
@RooJavaBean
@RooToString
@RooEntity
public class Answer {
@PersistenceContext
transient EntityManager entityManager;
@Transactional
public void persist() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.persist(this);
}
@Transactional
public void remove() {
if (this.entityManager == null) this.entityManager = entityManager();
if (this.entityManager.contains(this)) {
this.entityManager.remove(this);
} else {
Answer attached = Answer.findAnswer(this.id);
this.entityManager.remove(attached);
}
}
@Transactional
public Answer merge() {
if (this.entityManager == null) this.entityManager = entityManager();
Answer merged = this.entityManager.merge(this);
this.entityManager.flush();
return merged;
}
public static final EntityManager entityManager() {
EntityManager em = new Answer().entityManager;
if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
return em;
}
public static long countAnswers() {
return entityManager().createQuery("SELECT COUNT(o) FROM Answer o", Long.class).getSingleResult();
}
public static List<Answer> findAllAnswers() {
return entityManager().createQuery("SELECT o FROM Answer o", Answer.class).getResultList();
}
...
}
谢谢你的伟大的链接。它没有真正回答的唯一问题是第一个。目前还不清楚何时以及如何在每个实体中注入EntityManager。 –
@GuidoGarcía,你现在有答案吗? – eric2323223
@ eric2323223尚未 –