JPA + persistindo em um projeto WEB

Eu tenho os seguintes códigos e estou pegando NullPointerException no meu EntityManager em na classe BaseDAOImpl, por acaso estou fazendo algo errado, pois quando coloco direto no Servlet o @PersistentUnit emf e depois o EntityManager funciona e não vem Null, a partir que abstraio e coloco em um DAO ele começa a dar como NullPointerException, provavelmente estou fazndo algo de errado mas como fazer funcionar no cso de projeto web? Alguém pode me dizer? Precisa do web.xml e persistence.xml? Vou colocar via das dúvidas.

Pra detalhe, estou usando glassfish, as configuirações de senha e tale stá ok, tanto q funciona transação ou consulta no servlet somente quando absatraio que pego NullPointerException…

package com.citespace.citespacerest.dao;

import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.persistence.EntityExistsException;
import javax.persistence.TransactionRequiredException;

@Remote
public interface BaseDAO<T>  {  
    public List<T> listCountry();
}
package com.citespace.citespacerest.dao.impl;


import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;

import com.citespace.citespacerest.dao.BaseDAO;
import com.citespace.cms.model.Country;

@Stateless
public class BaseDAOImpl<T> implements BaseDAO<T>{


    @PersistenceUnit(unitName = "citespacePU")
    public EntityManagerFactory emf;
   
    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)

    public List<T> listCountry(){
       
        EntityManager em = emf.createEntityManager();
        try{
            Query q = em.createQuery("Select c from Country c ");

            List<Country> c =  q.getResultList();           
            return (List<T>) c;
        }finally{
                if (em != null && em.isOpen()) {
                    em.close();
                }
        }       
       
    }
}
package com.citespace.citespacerest;

import java.util.List;

import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;


import com.citespace.citespacerest.dao.impl.BaseDAOImpl;
import com.citespace.cms.model.Country;


@Path("/user/")
public class UserResource {
  
    @GET
    @Produces("text/plain")
    public String registerUser(){
      
           BaseDAOImpl<Country> countryDAO = new BaseDAOImpl<Country>();
           List<Country> c = countryDAO.listCountry();

            String y = "";            
              for(Country x: c){
                  y = y + ":" +x.getName();
              }                                                 
        
        return "[Lista de Países]:"+y;
    }
   
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.feature.Redirect</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>unit:citespacePU</param-name>
            <param-value>persistence/citespace</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/resources/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
	<welcome-file>
            index.jsp
        </welcome-file>
    </welcome-file-list>
    <persistence-unit-ref>
        <persistence-unit-ref-name>persistence/citespace</persistence-unit-ref-name>
        <persistence-unit-name>citespacePU</persistence-unit-name>
    </persistence-unit-ref>
    <resource-ref>
        <res-ref-name>UserTransaction</res-ref-name>
        <res-type>javax.transaction.UserTransaction</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>  
 </web-app>
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="citespacePU" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>    
	<jta-data-source>jdbc/TestDS</jta-data-source>
	<!-- <jar-file>/home/roan/Desktop/MyWorkspaces/workspace2/lib/citespace-persistence.jar</jar-file> -->
    <properties>       
          <property name="hibernate.hbm2ddl.auto" value="update"/>
          <property name="hibernate.connection.characterEncoding" value="UTF-8"/>  
  </persistence-unit>
</persistence>

StackTrace, sei que vocês vão pedir.

[#|2009-10-23T12:32:13.416-0200|SEVERE|sun-appserver2.1|javax.enterprise.system.container.web|_ThreadID=17;_ThreadName=httpSSLWorkerThread-8080-2;_RequestID=761422a8-75a1-4a48-8d70-6722f4306fe6;|StandardWrapperValve[Jersey Web Application]: PWC1406: Servlet.service() for servlet Jersey Web Application threw exception
java.lang.NullPointerException
	at com.citespace.citespacerest.dao.impl.BaseDAOImpl.listCountry(BaseDAOImpl.java:32)
	at com.citespace.citespacerest.UserResource.registerUser(UserResource.java:29)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:156)
	at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:67)
	at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:163)
	at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:71)
	at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:111)
	at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:63)
	at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:654)
	at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:612)
	at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:603)
	at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:309)
	at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:425)
	at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:590)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
	at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:427)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:315)
	at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:287)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:218)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
	at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:94)
	at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:98)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:222)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:587)
	at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1096)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:166)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:587)
	at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1096)
	at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:288)
	at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.invokeAdapter(DefaultProcessorTask.java:647)
	at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:579)
	at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.process(DefaultProcessorTask.java:831)
	at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.executeProcessorTask(DefaultReadTask.java:341)
	at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:263)
	at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:214)
	at com.sun.enterprise.web.portunif.PortUnificationPipeline$PUTask.doTask(PortUnificationPipeline.java:380)
	at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:265)
	at com.sun.enterprise.web.connector.grizzly.ssl.SSLWorkerThread.run(SSLWorkerThread.java:106)
|#]

Olá roanbrasil. só por desencargo, seu persistence.xml está dentro do diretorio META-INF ?
Como está seu jdbc/TestDS, poderia posta-lo.
Qual servidor de aplicação está usando ?

Opa walyson, tudo bem? O persistence.xml está ok e está dentro do META-INF tanto que como vou postar no exemplo abaixo ele funciona e acessa o banco… A partir do momento que tiro desse Servlet que faço request diretamente do Browser ele não funciona mais. O Servlet seria UserResource e a classe EJB BaseDAOImpl . Então no código abaixo funciona, só quando mudo que para de funcionar. O servidor de aplicação é glassfish uma vez que o jersey é da sun e tudo funciona mais prático.

Eu estou com um projeto utilizando Jersey Rest web services. Gerei o projeto com maven2 e estou usando o JPA. A classe Jersey se chama Resource que é nada mais nada menos que um Servlet. Por exemplo o resource: O código abaixo funciona normalmente.

@Path("/user/")
  public class UserResource {

    
     @PersistenceUnit(unitName="PU")
      EntityManagerFactory emf;


     @GET
     @Produces("text/plain")
     public String registerUser(){

      EntityManager em = emf.createEntityManager();
...  //consulta de código Query q= bla bla bla
 [b]@PersistenceUnit(unitName="PU")
  EntityManagerFactory emf;


  EntityManager em = emf.createEntityManager();

… //consulta de código Query q= bla bla bla[/b]

A partir do momento que tiro o que está em negrito no código acima e jogo em uma classe EJB @Stateless que implementa uma interface @Remote, simplesmente essa linha de chamada
EntityManager em = emf.createEntityManager();

que acrescentei na classe EJB, de nome por exemplo BaseDAOImpl, simplesmente dá uma exceção NullPointerException no EntityManager pois não conseguiu injetar da mesma forma o PersistenceUnit nessa classe como no exemplo acima.

Gostaria de saber como resolver esse problema?

Tenta fazer assim no seu BaseDAOImpl:

@PersistenceContext(unitName="citespacePU")
protected EntityManager em;  
package com.citespace.citespacerest.dao.impl;


import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.citespace.citespacerest.dao.BaseDAO;
import com.citespace.cms.model.Country;

@Stateless
public class BaseDAOImpl<T> implements BaseDAO<T>{

	
	@PersistenceContext(unitName = "citespacePU")
	protected EntityManager em;
	

	public List<T> listCountry(){
		
		
		List<Country> c = null;
		try{
			Query q = em.createQuery("Select c from Country c ");
	    	c =  q.getResultList();	    		    	
		}catch(NoResultException e){
			 System.err.println("NoResultException: " 
                     + e.getMessage());
		}catch(NonUniqueResultException e){
			System.err.println("NonUniqueResultException: " 
                    + e.getMessage());
		}catch(IllegalStateException e){
			System.err.println("IllegalStateException: " 
                    + e.getMessage());
		}
		finally{
				if (em != null && em.isOpen()) {
					em.close();
				}
		}	
		
		return (List<T>) c;
		
	}
}

fiz essa alteração e o erro continua …

olha o strack trace agora

está no query q o erro

5a3-5b46896d4645;|StandardWrapperValve[Jersey Web Application]: PWC1406: Servlet.service() for servlet Jersey Web Application threw exception
java.lang.NullPointerException
	at com.citespace.citespacerest.dao.impl.BaseDAOImpl.listCountry(BaseDAOImpl.java:39)
	at com.citespace.citespacerest.UserResource.registerUser(UserResource.java:29)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:156)
	at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:67)
	at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:163)
	at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:71)
	at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:111)
	at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:63)
	at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:654)
	at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:612)
	at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:603)
	at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:309)
	at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:425)
	at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:590)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
	at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:427)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:315)
	at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:287)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:218)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
	at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:94)
	at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:98)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:222)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:587)
	at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1096)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:166)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:587)
	at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1096)
	at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:288)
	at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.invokeAdapter(DefaultProcessorTask.java:647)
	at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:579)
	at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.process(DefaultProcessorTask.java:831)
	at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.executeProcessorTask(DefaultReadTask.java:341)
	at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:263)
	at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:214)
	at com.sun.enterprise.web.portunif.PortUnificationPipeline$PUTask.doTask(PortUnificationPipeline.java:380)
	at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:265)
	at com.sun.enterprise.web.connector.grizzly.ssl.SSLWorkerThread.run(SSLWorkerThread.java:106)
|#]