Reputation: 127
Trying to get my head around Java EE
(ORM/Entities/Annotations/EJB/Servlets etc.). So I've created a very simple webpage where you can enter user information and send it to the server. I'm using Apache Tomcat 8.0
as webbserver application and here is all the relevant parts of the application files and content that is needed to persist an entity:
The application gives me the error on line 99 saying:
08-Apr-2014 16:18:10.329 SEVERE [http-nio-8084-exec-93] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [indexServlet] in context with path [/JavaEENackademin] threw exception
java.lang.NullPointerException
What am I doing wrong? The database exist with the correct named table and columnnames. But then again that is not the problem here maybe it will become a problem after I fix this problem :)
Upvotes: 0
Views: 85
Reputation: 5306
I'm surprised you are able to deploy the code in your pastebin. Especially:
@WebServlet(name = "indexServlet", urlPatterns = {"/indexServlet"})
public class indexServlet extends HttpServlet {
@Inject
LoginValidation validation;
@PersistenceContext(unitName = "JavaEENackademinPU")
private EntityManager em;
//... offending line 99 calls: em.persist()
}
Neither PersistenceContext
nor Inject
are part of the servlet spec, so you probably added additional jars to your installation.
But you configured your persistence.xml
to use JTA transactions which are barely supported in a servlet environment, probably resulting in tomcat ignoring the @PersistenceContext
annotation altogether and leaving em == null
(the default value).
I've found this link describing an integration but it looks complicated, requires editing internal xml files and then goes on to use Spring. Likely every part of that is overkill for a beginner.
I suggest you start fresh with a copy of TomEE which already does all the wiring to get you a fully fledged application server that supports CDI (@Inject
) and JPA (@PersistenceContext
) out of the box.
Upvotes: 0
Reputation: 3343
One issue with your code is that you should not inject EntityManager
s into servlets. Servlets are usually singletons, so all servlets would use the same EntityManager
. You should inject an EntityManagerFactory
instead and get your EntityManager
s from it. You also have to take care of transactions. Not sure if this has caused your issues, but something that should be fixed.
Upvotes: 1