Usando JSF com JPA Hibernate apresenta java.lang.NullPointerException

Olá Pessoal,

Estou aprendendo JSF com JPA/Hibernate, fiz conforme um exemplo de uma apostila, mas
não consigo entender onde esta o erro, fico grato se alguém puder me ajudar

Meu arquivo persistence.xml

<?xml version="1.0" encoding = "UTF-8"?>
<persistence version = "2.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_2_0.xsd" >

<persistence-unit name ="biblioteca" transaction-type = "RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence </provider>
<properties>
<property name = "hibernate.dialect" value = "org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name = "hibernate.hbm2ddl.auto " value = "create" />
<property name = "javax.persistence.jdbc.driver" value = "com.mysql.jdbc.Driver " />
<property name = "javax.persistence.jdbc.user" value = "fabiano" />
<property name = "javax.persistence.jdbc.password" value = "150978" />
<property name = "javax.persistence.jdbc.url" value ="jdbc:mysql://localhost:3306/biblioteca"/>
</properties>
</persistence-unit>
</persistence>

Classe JPAFiltro

package br.com.biblioteca.filtro;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

@WebFilter(servletNames={"Faces Servlet"})
public class JPAFiltro implements Filter {

	private EntityManagerFactory fabrica;
	@Override
	public void destroy() {
		
		this.fabrica.close();

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {

		EntityManager gerenciar = this.fabrica.createEntityManager();
		arg0.setAttribute("EntityManager", gerenciar);
		gerenciar.getTransaction().begin();
		
		arg2.doFilter(arg0, arg1);
		
		try{
			
			gerenciar.getTransaction().commit();
		}
		catch(Exception e){
			gerenciar.getTransaction().rollback();
		}
		finally{
			gerenciar.close();
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

		this.fabrica = Persistence.createEntityManagerFactory("biblioteca");

	}

}

Minha classe bean Aluno


package br.com.biblioteca.beans;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;


@Entity
public class Aluno {
	
	@Id
	@Column(name="id")
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private long id;
	@Column(name="nome")
	private String nome;
	@Column(name="rg")
	private long rg;
	@Column(name="telefone")
	private String telefone;
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getNome() {
		return nome;
	}
	public void setNome(String nome) {
		this.nome = nome;
	}
	public long getRg() {
		return rg;
	}
	public void setRg(long rg) {
		this.rg = rg;
	}
	public String getTelefone() {
		return telefone;
	}
	public void setTelefone(String telefone) {
		this.telefone = telefone;
	}
	
}

Classe Aluno Repositório

package br.com.biblioteca.beans;

import javax.persistence.EntityManager;

public class AlunoRepositorio {

	private EntityManager gerenciar;
	
	public AlunoRepositorio(EntityManager gerenciar) {
		
		this.gerenciar = gerenciar;
	}
	
	public void adiciona(Aluno aluno){
		this.gerenciar.persist(aluno);
	}
}

Classe AlunoBeans

package br.com.biblioteca.managedbeans;

import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import br.com.biblioteca.beans.Aluno;
import br.com.biblioteca.beans.AlunoRepositorio;

@ManagedBean
public class AlunoBeans {

	private Aluno aluno = new Aluno();
	
	
	public void adicionaAluno(){
		
		EntityManager gerencia = this.getEntityManager();
		AlunoRepositorio repositorio = new AlunoRepositorio(gerencia);
		repositorio.adiciona(this.aluno);
		
	}
	
	
	private EntityManager getEntityManager(){
		
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ec = fc.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ec.getRequest(); 
		EntityManager gerencia = (EntityManager) request.getAttribute("EntityManager");
		
		return gerencia;
	}

	public Aluno getAluno() {
		return aluno;
	}

	public void setAluno(Aluno aluno) {
		this.aluno = aluno;
	}
	
	
}

Minha JSF

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core">
<h:head>

<title>SistemaBiblioteca-Aluno</title>
</h:head>
<h:body>

<h:form id="cadastrarAluno">

<h1>Cadastro de Aluno</h1>
<table>
<tr>
<td><h:outputLabel value="Aluno" /></td>
<td><h:inputText value="#{alunoBeans.aluno.nome}" required="true" id="nome" /></td>
</tr>
<tr>
<td><h:outputLabel value="RG" /></td>
<td><h:inputText value="#{alunoBeans.aluno.rg}" required="true" id="rg" /></td>
</tr>
<tr>
<td><h:outputLabel value="Telefone" /></td>
<td><h:inputText value="#{alunoBeans.aluno.telefone}" required="true" id="telefone" /></td>
</tr>
<tr>
<td></td>
<td><h:commandButton value="Cadastrar" action="#{alunoBeans.adicionaAluno()}"/></td>
</tr>
</table>
</h:form>
</h:body>


</html>

A mensagem de erro que apresenta
O erro apresenta na parte em negrito, mas não consigo fazer funcionar.

Mai 03, 2012 7:41:03 PM com.sun.faces.application.ActionListenerImpl processAction
Grave: java.lang.NullPointerException
javax.faces.el.EvaluationException: java.lang.NullPointerException
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
	at javax.faces.component.UICommand.broadcast(UICommand.java:315)
	at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:787)
	at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1252)
	at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
	at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
	at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.NullPointerException
	at br.com.biblioteca.beans.AlunoRepositorio.adiciona(AlunoRepositorio.java:15)
	at br.com.biblioteca.managedbeans.AlunoBeans.adicionaAluno(AlunoBeans.java:22)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:601)
	at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
	at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
	at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
	... 24 more

Mai 03, 2012 7:41:03 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
Advertência: #{alunoBeans.adicionaAluno()}: java.lang.NullPointerException
javax.faces.FacesException: #{alunoBeans.adicionaAluno()}: java.lang.NullPointerException
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
	at javax.faces.component.UICommand.broadcast(UICommand.java:315)
	at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:787)
	at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1252)
	at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
	at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
	at java.lang.Thread.run(Thread.java:722)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
	... 23 more
Caused by: java.lang.NullPointerException
	[b]at br.com.biblioteca.beans.AlunoRepositorio.adiciona(AlunoRepositorio.java:15)
	at br.com.biblioteca.managedbeans.AlunoBeans.adicionaAluno(AlunoBeans.java:22)[/b]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:601)
	at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
	at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
	at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
	... 24 more

Para você descobrir onde está o erro, na maioria das vezes basta olhar o log.

No seu caso o erro está aqui at br.com.biblioteca.beans.AlunoRepositorio.adiciona(AlunoRepositorio.java:15) .

this.gerenciar.persist(aluno);

Parece que você não instanciou o entityManager

[quote=jakefrog]Para você descobrir onde está o erro, na maioria das vezes basta olhar o log.

No seu caso o erro está aqui at br.com.biblioteca.beans.AlunoRepositorio.adiciona(AlunoRepositorio.java:15) .

this.gerenciar.persist(aluno);

Parece que você não instanciou o entityManager[/quote]

Esta sim instanciado porém, não sei onde esta o erro.

Bem, o erro aponta ali. O erro diz que ele não foi instanciado… Tá estranho isso. =/

Você pode fazer um teste?

Acima da linha this.gerenciar.persist(aluno); coloque isso aqui:System.out.println("Objeto EntityManager: " + gerenciar);O que imprime no console?

[quote=jakefrog]Bem, o erro aponta ali. O erro diz que ele não foi instanciado… Tá estranho isso. =/

Você pode fazer um teste?

Acima da linha this.gerenciar.persist(aluno); coloque isso aqui:System.out.println("Objeto EntityManager: " + gerenciar);O que imprime no console?[/quote]

Então esta retornando: Objeto EntityManager: null

Ou seja, ele não está instanciado. [=

Ao invés de usar request, tente coloca o session.

Mas isso que você está fazendo ñ é uma boa prática viu. =/

Poxa eu não sei se seria melhor eu abrir um tópico novo, se for o caso eu abro sem problemas, mas é que eu estou tendo o mesmo problema, mas não consegui solucionar a falha mudando o escopo de request para session na classe bean.

O LOG do Glassfish:
BOM: /carros.xhtml @9,9 <h:head> Component[552647270_20f0ba7c] Created: javax.faces.component.UIOutput
BOM: /carros.xhtml @13,9 <h:body> Component[552647270_20f0ba52] Created: javax.faces.component.UIOutput
BOM: /carros.xhtml @14,10 <h:form> Component[552647270_20f0ba28] Created: javax.faces.component.html.HtmlForm
BOM: /carros.xhtml @15,28 <h:panelGrid> Component[552647270_20f0ba0e] Created: javax.faces.component.html.HtmlPanelGrid
BOM: /carros.xhtml @16,55 <h:outputLabel> Component[552647270_20f0bae4] Created: javax.faces.component.html.HtmlOutputLabel
BOM: /carros.xhtml @17,69 <h:inputText> Component[552647270_20f0bae9] Created: javax.faces.component.html.HtmlInputText
BOM: /carros.xhtml @19,57 <h:outputLabel> Component[552647270_20f0bafa] Created: javax.faces.component.html.HtmlOutputLabel
BOM: /carros.xhtml @20,71 <h:inputText> Component[552647270_20f0bacf] Created: javax.faces.component.html.HtmlInputText
BOM: /carros.xhtml @23,43 <h:commandButton> Component[552647270_20f0bad0] Created: javax.faces.component.html.HtmlCommandButton

BOM: /carros.xhtml @9,9 <h:head> Component[552647270_20f0ba7c] Created: javax.faces.component.UIOutput
BOM: /carros.xhtml @13,9 <h:body> Component[552647270_20f0ba52] Created: javax.faces.component.UIOutput
BOM: /carros.xhtml @14,10 <h:form> Component[552647270_20f0ba28] Created: javax.faces.component.html.HtmlForm
BOM: /carros.xhtml @15,28 <h:panelGrid> Component[552647270_20f0ba0e] Created: javax.faces.component.html.HtmlPanelGrid
BOM: /carros.xhtml @16,55 <h:outputLabel> Component[552647270_20f0bae4] Created: javax.faces.component.html.HtmlOutputLabel
BOM: /carros.xhtml @17,69 <h:inputText> Component[552647270_20f0bae9] Created: javax.faces.component.html.HtmlInputText
BOM: /carros.xhtml @19,57 <h:outputLabel> Component[552647270_20f0bafa] Created: javax.faces.component.html.HtmlOutputLabel
BOM: /carros.xhtml @20,71 <h:inputText> Component[552647270_20f0bacf] Created: javax.faces.component.html.HtmlInputText
BOM: /carros.xhtml @23,43 <h:commandButton> Component[552647270_20f0bad0] Created: javax.faces.component.html.HtmlCommandButton
AVISO: #{carroBean.adicionaCarro}: java.lang.NullPointerException
javax.faces.FacesException: #{carroBean.adicionaCarro}: java.lang.NullPointerException
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1542)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:619)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
… 31 more
Caused by: java.lang.NullPointerException
at model.CarroRepository.adiciona(CarroRepository.java:17)
at managedbeans.CarroBean.adicionaCarro(CarroBean.java:21)
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.el.parser.AstValue.invoke(AstValue.java:254)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
… 32 more

AVISO: StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception
java.lang.NullPointerException
at model.CarroRepository.adiciona(CarroRepository.java:17)
at managedbeans.CarroBean.adicionaCarro(CarroBean.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

Minha classe repositório:

package model;

import java.util.*;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class CarroRepository {

private EntityManager manager;

public CarroRepository(EntityManager manager){
	this.manager = manager;
}

public void adiciona(Carro carro){
	this.manager.persist(carro);
}


public List<Carro> buscaTodos(){
	Query query = this.manager.createQuery("select x from carro x");
	return query.getResultList();
}

}

Minha classe bean:

package managedbeans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import model.Carro;
import model.CarroRepository;

@SessionScoped
@ManagedBean
public class CarroBean {

private Carro carro = new Carro();

public void adicionaCarro() {
	EntityManager manager = this.getEntityManager();
	CarroRepository repository = new CarroRepository(manager);

	repository.adiciona(this.carro);
	this.carro = new Carro();
}

public List<Carro> getCarros() {
	EntityManager manager = this.getEntityManager();
	CarroRepository repository = new CarroRepository(manager);
	return repository.buscaTodos();
}

private EntityManager getEntityManager() {
	FacesContext fc = FacesContext.getCurrentInstance();
	ExternalContext ec = fc.getExternalContext();
	HttpServletRequest request = (HttpServletRequest) ec.getRequest();
	EntityManager manager = (EntityManager)request.getAttribute("EntityManager");

	return manager;
}

public Carro getCarro() {
	return carro;
}

public void setCarro(Carro carro) {
	this.carro = carro;
}

minha página jsf:

<h:head>
Página aqui
</h:head>

<h:body>
<h:form>
<h:panelGrid columns=“2”>
<h:outputLabel value=“Marca: " for=“campo-marca” />
<h:inputText value=”#{carroBean.carro.marca}" id=“campo-marca” />

		<h:outputLabel value="Modelo: " for="campo-modelo" />
		<h:inputText value="#{carroBean.carro.modelo}" id="campo-modelo" />

		<h:commandButton value="Adicionar"
			action="#{carroBean.adicionaCarro}" />
	</h:panelGrid>
</h:form>

</h:body>

Se alguém puder me explicar como solucionar a falha… Parece que o Log do glasfish deixa claro que está no método adiciona da classe repositório, mas mesmo assim eu não estou encontrando a solução, se for falta de instanciar a EntityManager onde eu devo fazer? Desculpa ressuscitar esse tópico, mas eu fiquei o fim de semana inteiro nesse código pensando que o problema poderia até estar no mysql que não aceitava persistir os dados, mas não sei… Se alguém puder me ajudar eu agradeço.