I have one database, but the atomicity of transactions is large. In other words, many entities must be manipulated in one transaction. Therefore, the design is something like that:
- a general superclass entity that holds shared stuff amongst all other entities that are subject to be persisted.
- an entity manager class that is responsible for creation of emf and em.
- a general dao for the superclass mentioned above, to accomplish shared, general persistence tasks (crud operations - create, retrieve, update, delete ). The entity class type and an entity manager is injected to this dao.
- specific dao classes for entities that needs operations other than crud. Something to note down is that since transaction management must be done in an upper layer in this case, no begin, commit or rollback transaction operation appear at dao (persistence) layer.
// general superclass
@MappedSuperclass
public class MyBean implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id = -1L;
// ...
}
//////////////////////////////////////////////////////////////
// a specific class
public class SpecificBean extends MyBean {
// ...
}
//////////////////////////////////////////////////////////////
// entity manager class
public class MyEntityManager {
private static final String PERSISTENCE_UNIT = "MyPU";
@PersistenceUnit(unitName = PERSISTENCE_UNIT)
private EntityManagerFactory emf;
public EntityManager getEm() {
if (emf == null) {
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
}
return emf.createEntityManager();
}
}
//////////////////////////////////////////////////////////////
// general dao for superclass MyBean
public class MyBeanDao {
private Class clazz;
protected EntityManager em;
public MyBeanDao(Class clazz, EntityManager em) {
this.clazz = clazz;
this.em = em;
}
public void create(MyBean bean) {
em.persist(bean);
}
public MyBean retrieve(Long id) {
return (MyBean) em.find(this.clazz, id);
}
public void remove(Long id) {
MyBean bean = retrieve(id);
if (bean != null) {
em.remove(bean);
}
}
public MyBean update(MyBean bean) {
MyBean updated = em.merge(bean);
return updated;
}
public void closeEm() {
em.close();
}
public void initTransaction() {
em.getTransaction().begin();
}
public void finishTransaction() {
em.getTransaction().commit();
}
public void rollbackTransaction() {
em.getTransaction().rollback();
}
}
//////////////////////////////////////////////////////////////
// specific dao classes
public class SpecificDao extends MyBeanDao {
public SpecificDao (EntityManager em) {
super(SpecificBean.class, em);
}
// extra methods
}
//////////////////////////////////////////////////////////////
// sample call
MyEntityManager mem = new MyEntityManager ();
EntityManager em = mem.getEm();
SpecificDao dao = new SpecificDao (em);
dao.initTransaction();
// do something
// ....
dao.finishTransaction();
more effective solutions may exist.. this is just a sample design..
Hiç yorum yok:
Yorum Gönder