Hi,
I'm new to EJB 3.0 and just learning about the new persistence features. I'm
using Eclipse 3.2 with JBoss 4.05 as the application server. I'm currently
trying to write a very simple servlet listener class, which should fetch one
row from a database using the EntityManagerFactory and EntityManager classes.
This is very similar to the material represented in the latest Java EE tutorial
(it's using the same database as the web bookstore example). Here's the code
for that class:
| public class ContextListener implements ServletContextListener {
| @javax.persistence.PersistenceUnit(unitName="pu") private
EntityManagerFactory emf;
|
| public void contextDestroyed(ServletContextEvent arg0) { }
|
| public void contextInitialized(ServletContextEvent arg0) {
| EntityManager em = emf.createEntityManager();
| WebBookstoreBooks b =
(WebBookstoreBooks)em.find(WebBookstoreBooks.class, "201");
| System.out.println(b.getTitle());
| }
| }
|
And here's my persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
| <persistence xmlns="http://java.sun.com/xml/ns/persistence" ...>
| <persistence-unit name="pu">
| <jta-data-source>java:/sqlserver</jta-data-source>
| <class>data.WebBookstoreBooks</class>
| </persistence-unit>
| </persistence>
After deployment I get NullPointerException from this line:
EntityManager em = emf.createEntityManager();
If I understand correctly, this means, that the EntityManagerFactory has not
been injected and is null. Anyhow, if I write the same code and add the bolded
line there, everything works:
| public class ContextListener implements ServletContextListener {
| @javax.persistence.PersistenceUnit(unitName="pu") private
EntityManagerFactory emf;
|
| public void contextDestroyed(ServletContextEvent arg0) { }
|
| public void contextInitialized(ServletContextEvent arg0) {
|
| emf = Persistence.createEntityManagerFactory("pu");
|
| EntityManager em = emf.createEntityManager();
| WebBookstoreBooks b =
(WebBookstoreBooks)em.find(WebBookstoreBooks.class, "201");
| System.out.println(b.getTitle());
| }
| }
|
This is very confusing. Why do I have to "manually" create the
EntityManagerFactory by calling Persistence.createEntityManagerFactory?
Shouldn't the container (JBoss) do that automatically. I've googled and found
dozens of examples, where the EntityManagerFactory is just added with the
@persistenceUnit annotation and everything works fine after that without the
need for any extra lines of code.
Could someone explain what is going on here and if I'm doing/understood
something wrong?
View the original post :
http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4004589#4004589
Reply to the post :
http://www.jboss.com/index.html?module=bb&op=posting&mode=reply&p=4004589
_______________________________________________
jboss-user mailing list
[email protected]
https://lists.jboss.org/mailman/listinfo/jboss-user