
Originally Posted by
Ben Alex
If having persistence methods in entities was really a major problem, a lot of Rails projects seem to be working perfectly successfully regardless.
I personally don't see any problem in having persistence methods in an Entity, simply because we're not doing much there but delegating to the EntityManager. So concerns are separated for the most part.
In a related vein, in case one/Roo creates an abstract base entity that sports the id and version fields, would it be appropriate to put a (protected) entityManager field and the generic persist(), update() and remove methods there as well? Something along the lines of:
Code:
@Configurable
@MappedSuperclass
public abstract class PersistentObject {
@Transient
@PersistenceContext
protected EntityManager entityManager;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Version
@Column(name = "version")
private Integer version;
public final Long getId() {
return this.id;
}
public final void setId(Long id) {
this.id = id;
}
public final Integer getVersion() {
return this.version;
}
public final void setVersion(Integer version) {
this.version = version;
}
@Transactional
public void persist() {
this.entityManager.persist(this);
}
@Transactional
public void remove() {
PersistentObject object;
if (this.entityManager.contains(this)) {
object = this;
} else {
object = this.entityManager.find(getClass(), this.id);
}
this.entityManager.remove(object);
}
@Transactional
public void update() {
PersistentObject merged = this.entityManager.merge(this);
this.entityManager.flush();
this.id = merged.getId();
}
public static EntityManager entityManager() {
return new EntityManagerHolder().entityManager;
}
private static class EntityManagerHolder extends PersistentObject {
}
}
Cheers,
Jukka