The code below is what Spring Roo generates by default, the EntityManager is injected in your domain model POJOs with the rest of the methods to manage the entity (save, update, delete, findXXX, ...).
Maybe it is a more object-oriented approach (in contrast to the anemic domain model), but what I don't understand is:
Is there any performance issue when EntityManager is injected in every entity (imagine you retrieve 1000 entities from a database)
Shouldn't the transactional management (@Transactional annotations) go in a service layer? (imagine you want to operate with two different entities in an atomic way).
Can you think about other pros/cons of this code against a classical DAO layer?
The code looks like this (some methods are removed for clarity):
@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();
}
...
}