Gui*_*ido 6 dao jpa spring-roo
下面的代码是Spring Roo默认生成的代码,EntityManager在您的域模型POJO中注入了其余的方法来管理实体(保存,更新,删除,findXXX,...).
也许这是一种更加面向对象的方法(与贫血领域模型相反),但我不明白的是:
在每个实体中注入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();
}
...
}
Run Code Online (Sandbox Code Playgroud)
您可以在第三点的链接中找到更多相关信息。
在典型的 Roo 应用程序中您没有服务层。您的服务方法包含在实体本身内,因此可以@Transactional
在实体内使用以确保特定方法涉及事务。但是,您将能够通过最新的 1.2 版本的 Spring Roo 获得单独的服务层,这将使其成为可能。
ADM 与 DDD :关于 SO 的单独问题将对此有所帮助。不管怎样,您可以通过 SpringSource Roo 论坛上的这个帖子获得很多见解。 http://forum.springsource.org/showthread.php?77322-Spring-Roo-with-a-services-DAO-architecture
干杯,祝 Roo 一切顺利!:)
归档时间: |
|
查看次数: |
3889 次 |
最近记录: |