quick question:
I have webapplication (wicket+spring+jpa) and was thinking about rather unusual architecture design. Please check it out and give your comments.
Consider class Wrapper:
@Service
public class Wrapper {
protected static EntityManager entityManager;
@PersistenceContext
private void injectEntityManager(EntityManager entityManager) {
Wrapper.entityManager = entityManager;
}
as you see I have now EntityManager injected statically.
Now consider simple entity DogEntity
@Entity
public class DogEntity {
String name;
}
And for that entity we create wrapper Dog
public class Dog extends Wrapper {
private DogEntity entity;
private Dog(DogEntity entity) {
this.entity = entity;
}
public static Dog create(String name) {
entity = new DogEntity();
entity.name = name;
entityManager.persist(entity); // for a moment forget that this code is not in transaction
return new Dog(entity);
}
}
Now in my webapplication (in my controller) I can do something like this:
saveButton = new Button("save") {
public void onSubmit() {
Dog dog = Dog.create(name);
// other code
}
From code point of view this architecture looks perfect. We have wrappers representing business objects. They all have persistent state, there are no stupid services in application called DogSaver with method save(DogEntity) which only call persist on entity manager. Code really gets a lot of readability and there some other advantages, but I dont wont go into details.
What really is my concern is this static EntityManager. I do not have enough knowledge about internals of Spring to know whether this approach is proper and safe. Are there situations where things mihgt get ugly?
I know that EntityManare is stateless (according to JPA spec), it always takes persistence context from transaction, thus making it static does not seem a bad idea. But I fear that I might be messing something.
Any thoughts?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…