I want to use container managed transaction in one class and share it with its subclasses.
Here is my abstract class :
@TransactionManagement(TransactionManagementType.CONTAINER)
public abstract class AbstractDAO {
@PersistenceContext(unitName = "myDS")
protected EntityManager em;
@Resource
protected SessionContext context;
protected Logger log;
public AbstractDAO() {
log = LoggerFactory.getLogger(this.getClass());
}
}
One of its child :
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class OrdreDAO extends AbstractDAO {
public OrdreDAO() {
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void persist(Ordre o) {
em.persist(o);// NPE here ... no EntityManager injected !
}
@SuppressWarnings("unchecked")
public List<Ordre> findAll() {
Query q = em.createQuery("from Ordre");
return q.getResultList();
}
}
On top of this child , OrdreService :
public class OrdreService {
private OrdreDAO dao;
public OrdreService() {
dao=new OrdreDAO();
}
public void persist(Ordre o) {
System.out.println("Service::persist ??");
dao.persist(o);
}
public List<Ordre> getOrdres() {
return dao.findAll();
}
public Ordre getOrdre(String id) {
return dao.findByPK(id);
}
public Ordre merge(Ordre o) {
return dao.merge(o);
}
}
A servlet using it :
public class creerOrdre extends HttpServlet {
private static final long serialVersionUID = 1L;
private OrdreService os;
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
System.out.println("création ordre");
Ordre o = new Ordre();
o.setDate(req.getParameter("date"));
o.setMotif(req.getParameter("motif"));
System.out.println("Ordre: " + o.getDate() + " " + o.getMotif());
OrdreService os = new OrdreService()
if (os!=null) {
System.out.println("NON null !");
}
os.persist(o);
resp.sendRedirect("visualiser.jsp");
} catch (ParseException pe) {
throw new ServletException(pe);
}
}
}
I get a NPE when I try to persist an Ordre
What am I missing ?
JDK 6
JBoss 5.1.0.GA
JPA 1
Your
OrdreServicePOJOclass is not managed by the web container, and also it seems to me that it’s a useless additional layer. I would use only theOrdreDAO.Anyway if you want to keep both classes, make
OrdreServiceaStatelessEJB. Inject inOrdreServicetheOrdreDAOinstance using:Finally, inject
OrdreServicein your servlet using:This should work.