Understanding Entity Code Created by Spring Roo for GWT

We are working on a GWT project generated by Spring Roo , but we no longer use Roo to edit / generate classes. Instead, we now write everything by hand.

For each server-side entity class, Roo generates a rather strange EntityManager retrieval code. And in order to support him, I would like to understand this well, but I do not. The following are snippets of code for the generated object:

 @PersistenceContext transient EntityManager entityManager; public static final EntityManager entityManager() { EntityManager em = new Scenario().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; } @Transactional public void persist() { if (entityManager == null) entityManager = entityManager(); entityManager.persist(this); } public static List<Scenario> findAllScenarios() { List<Scenario> res = entityManager().createQuery( "select o from Scenario o order by o.name", Scenario.class).getResultList(); return res; } public static Scenario findScenario(Long id) { if (id == null) return null; return entityManager().find(Scenario.class, id); } 

My observations and questions:

  • Instance methods use the EntityManager field introduced by Spring, and this is understandable. But why is this piece for: if(entityManager == null) entityManager = entityManager(); ? Could we assume that the EntityManager field in em must be entered and cannot be null (otherwise is there something wrong?)
  • The static method creates a new instance of the object and gets its EntityManager field, why? Can't the EntityManager be cached in a static field or something like this?
  • Why read methods like findAllXXX not @Transictional ? From what I know, according to the JPA specification, should all JPA operations be performed as part of a transaction?
  • there is if (id == null) return null; thing in findXXX methods that are really needed? Shouldn't we break the application if we get null as the id parameter to show that something is wrong?
  • Can we rewrite this EntityManager receive code in a more elegant way (for example, without this strange new Entity().entityManager material), but without breaking it (maybe there are some premises that need to be preserved)?
  • Why is the EntityManager field transient ? It is important?
+4
source share
1 answer

I completely agree with you, the code looks very suspicious.

The usual way to use EntityManagers in DAO and @Transactional with Spring is beautifully explained in http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/dao.html and http: // static. springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html and I don't understand why this should be different for the code generated by Roo.

0
source

Source: https://habr.com/ru/post/1411111/


All Articles