I would like to equip my EJBs with CRUD methods.
I have many entities and multiple persistence units.
I want to implement my CRUD methods once and invoke them on different persistence units.
I tried to achieve this using inheritance, but it isn't working.
The CRUD class is:
public class FormEBean<T> {
protected EntityManager em;
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
public String create(T entity) {
try {
em.persist(entity);
em.flush();
return null;
} catch (Exception ex) {
return ex.getLocalizedMessage();
}
}
public void create(List<T> entityList) {
for (T entity : entityList) {
em.persist(entity);
}
}
public void edit(T entity) {
em.merge(entity);
}
public void edit(Set<T> entitySet) {
Iterator<T> it = entitySet.iterator();
while (it.hasNext()) {
T entity = it.next();
em.merge(entity);
}
}
public void remove(T entity) {
em.remove(em.merge(entity));
}
public void remove(T[] listaDaRimuovere) {
for (T entity : listaDaRimuovere) {
em.remove(em.merge(entity));
}
}
public void remove(List<T> listaDaRimuovere) {
for (T entity : listaDaRimuovere) {
em.remove(em.merge(entity));
}
}
}
So I tryed in this way:
@Stateless
@Remote(MyEBeanRemote.class)
public class MyEBean extends FormEBean<MyEntityClass> implements MyEBeanRemote {
@PersistenceContext(unitName = "siat-ejbPU")
private EntityManager em;
// code here
}
Even if I haven't got any error, the CRUD functions have no effect on my DataBase.
Instead if I insert them directly into MyEBean it behaves as expected.
I don't want to use @PersistenceContext(unitName = "siat-ejbPU")
in the FormEBean, because EJBs could use different persistence units.
Is there a way to solve this problem?
Is there a pattern I can use to reuse my code?
Edit:
The aim of this question is finding a solution that maximizes CRUD code reuse in EJBs belonging to different EJB modules and having different persistence units.
Using generic methods in a stateless session bean seems like a good solution, but only for reusing CRUD code for EJBs in the same persistence unit.
What solution could be persistence unit independent (if it exists)?