You should have a look at Spring Roo. They have something simular (no DAOs or Services), but there EntityManager is not static.
They do the trick with the @Configurable annotation in Entities:
@Entiy
@Configurable
class MyEntity() {
@PersistenceContext
transient EntityManager Car.entityManager;
...
public static MyEntity findMyEntityById(Long id) {
if (id == null) return null;
return entityManager().find(MyEntity.class, id);
}
public static EntityManager entityManager() {
EntityManager em = new MyEntity().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;
}
}
Anyway it has two or three drawbacks:
you need AspectJ
this line EntityManager em = new MyEntity().entityManager; is very ugly
testing becomes a bit difficult if you want to mock the persistent "layer". But fortunally the Spring provides a special AOP Interceptor (@see JavaDoc of org.springframework.mock.staticmock.AnnotationDrivenStaticEntityMockingControl)
But it has also some nice effects: for example the persist and delete methods become very natural, they are just member of the entity:
@Transactional
public void persist() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.persist(this);
}
To make a none Roo project aviable for @Configurable you need to at LEAST doing this: