JSF + Hibernate

13 respostas
L

Pessoal,

estou começando agora usar o JSF, e já estou obtendo problemas, rs.

Tenho a pagina xhtml

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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:h="http://java.sun.com/jsf/html"  
    xmlns:f="http://java.sun.com/jsf/core"  
    xmlns:p="http://primefaces.org/ui" > 
	<h:head>
    </h:head>
    <h:body>
    	<h:form>
	    	<h:panelGroup>
		    	<p:panelGrid id="panelEdit" columns="2">
		    		<h:outputLabel value="Nome:"/>
		    		<p:inputText id="inptNome" value="#{teste.pessoa.nome}"/>
		    		<h:outputLabel value="Idade:"/>
		    		<p:inputText id="inptIdade" value="#{teste.pessoa.idade}"/>  
		    	</p:panelGrid>
		    	<p:commandButton value="CADASTRAR" action="#{teste.salvar}" process="@this, panelEdit" update="panelView"/>
				<p:panelGrid id="panelView" columns="2">
					<h:outputLabel value="Nome Informado: "/>
		    		<h:outputText id="ouptNome" value="#{teste.pessoa.nome}"/>
		    		<h:outputLabel value="Idade Infomada: "/>
		    		<h:outputText id="ouptIdade" value="#{teste.pessoa.idade}"/>
				</p:panelGrid>
	    	</h:panelGroup>    		
    	</h:form>

    </h:body>   
</html>
A classe ManagedBean
@ManagedBean(name = "teste")  
public class TesteMB {  	
  
    private Pessoa pessoa = new Pessoa();  
    private PessoaDao pessoaDao = new PessoaDao();    
    public TesteMB() {  
          
    }
    
    public void salvar(){
    	pessoaDao.salvar(pessoa);
    	
    	System.out.println("salvar MB");
    
    }
              //getters and setters
}
A entidade Pessoa
public class Pessoa{
	@Id
	@GeneratedValue
	@Column (name="pessoa_id")
	private int id;
	
	@Column (name="pessoa_nome")
	private String nome;
	
	@Column (name="pessoa_idade")
	private int idade;
	
	//getters and setters
	
}
e a PessoaDao
public class PessoaDao {
	
	private static Session sessao = HibernateUtil.getSessionFactory()
			.openSession();

	public void salvar(Pessoa pessoa) {
		
		Transaction t = sessao.beginTransaction();
		
		try{
			sessao.save(pessoa);
			t.commit();			
		}catch(Exception e){
			t.rollback();
			e.printStackTrace();			
		}finally{
			sessao.close();
		}	
	}
}
o erro que é dado é este:
Caused by: javax.faces.FacesException: #{teste.submit}: java.lang.NullPointerException

Alguém poderia me ajudar? Creio que não seja uma coisa difícil.

Valeu pessoa! :wink:

13 Respostas

drsmachado
public class TesteMB {   
  
    private Pessoa pessoa = new Pessoa();     
    PessoaDao pessoaDao = new PessoaDao();   
    public TesteMB() {   
           
    }     
    public void submit(){         
        pessoaDao.salvar(pessoa);   
    }   
              //getters and setters   
}
L

alterei isso que tu falou machado, ficando a classe assim:

@ManagedBean(name = "teste")
public class TesteMB {

	private Pessoa pessoa = new Pessoa();
    private PessoaDao pessoaDao = new PessoaDao();  
	public TesteMB() {
		
	}	
	public void submit(){		
		getPessoaDao().salvar(pessoa);
		
	}

	//getters and setters
}
só que agora, o erro dado é esse:
Caused by: java.lang.ClassNotFoundException: org.hibernate.cfg.AnnotationConfiguration

Que a classe não existe, mas tanto meu hibernate.xfg.xml e a classe HibernateUtil estão criadas, o que fiz de errado?

Valeu pela ajuda! :!:

fabiozanardi

os jars do hibernate estão na pasta lib da sua app?

L

realmente os jars do hibernate, não estavam na pasta lib,

agora só falta o hibernate inserir os valores na tabela, ele cria a tabela mais não está inserindo.

Onde será que estou errando?

Obrigado! :!:

L

aqui está parte das informações que aparecem no console:

INFO: Hibernate Annotations 3.2.0.GA
GRAVE: 62 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.Environment - Hibernate 3.3.1.GA
GRAVE: 62 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.Environment - hibernate.properties not found
GRAVE: 62 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
GRAVE: 78 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
GRAVE: 218 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
GRAVE: 218 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
GRAVE: 437 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
INFO: Binding entity from annotated class: model.Pessoa
INFO: Bind entity model.Pessoa on table pessoa
GRAVE: 874 [http-thread-pool-8888-(2)] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)
GRAVE: 874 [http-thread-pool-8888-(2)] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 1
GRAVE: 874 [http-thread-pool-8888-(2)] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false
GRAVE: 874 [http-thread-pool-8888-(2)] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/residenciajsf
GRAVE: 874 [http-thread-pool-8888-(2)] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=root, password=****}
GRAVE: 1765 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - RDBMS: MySQL, version: 5.5.20
GRAVE: 1765 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.17 ( Revision: ${bzr.revision-id} )
GRAVE: 1796 [http-thread-pool-8888-(2)] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQLDialect
GRAVE: 1812 [http-thread-pool-8888-(2)] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions)
GRAVE: 1812 [http-thread-pool-8888-(2)] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
GRAVE: 1812 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
GRAVE: 1812 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
GRAVE: 1812 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
GRAVE: 1812 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
GRAVE: 1812 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
GRAVE: 1812 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
GRAVE: 1812 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto
GRAVE: 1812 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2
GRAVE: 1812 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
GRAVE: 1812 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
GRAVE: 1812 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
GRAVE: 1812 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
GRAVE: 1812 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
GRAVE: 1827 [http-thread-pool-8888-(2)] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
GRAVE: 1827 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
GRAVE: 1827 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled
GRAVE: 1827 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
GRAVE: 1827 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled
GRAVE: 1827 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
GRAVE: 1827 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
GRAVE: 1827 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
GRAVE: 1827 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout
GRAVE: 1843 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled
GRAVE: 1843 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
GRAVE: 1843 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
GRAVE: 1843 [http-thread-pool-8888-(2)] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled
GRAVE: 1921 [http-thread-pool-8888-(2)] INFO org.hibernate.impl.SessionFactoryImpl - building session factory
GRAVE: 2202 [http-thread-pool-8888-(2)] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
GRAVE: 2218 [http-thread-pool-8888-(2)] INFO org.hibernate.tool.hbm2ddl.SchemaUpdate - Running hbm2ddl schema update
GRAVE: 2218 [http-thread-pool-8888-(2)] INFO org.hibernate.tool.hbm2ddl.SchemaUpdate - fetching database metadata
GRAVE: 2218 [http-thread-pool-8888-(2)] INFO org.hibernate.tool.hbm2ddl.SchemaUpdate - updating schema
GRAVE: 2249 [http-thread-pool-8888-(2)] INFO org.hibernate.tool.hbm2ddl.TableMetadata - table found: residenciajsf.pessoa
GRAVE: 2249 [http-thread-pool-8888-(2)] INFO org.hibernate.tool.hbm2ddl.TableMetadata - columns: [pessoa_id, pessoa_idade, pessoa_nome]
GRAVE: 2249 [http-thread-pool-8888-(2)] INFO org.hibernate.tool.hbm2ddl.TableMetadata - foreign keys: []
GRAVE: 2249 [http-thread-pool-8888-(2)] INFO org.hibernate.tool.hbm2ddl.TableMetadata - indexes: [primary]
GRAVE: 2249 [http-thread-pool-8888-(2)] INFO org.hibernate.tool.hbm2ddl.SchemaUpdate - schema update complete

INFO: Updating configuration from org.apache.felix.fileinstall-autodeploy-bundles.cfg
INFO: Installed C:\glassfishv3\glassfish\modules\autostart\org.apache.felix.fileinstall-autodeploy-bundles.cfg

Agradeço a ajuda e peço desculpas pela ignorancia nessa parte, rs

leonhard32

Posta o erro ai pra gente ver :slight_smile:

L

Isso é tudo que ele retorna no console leonhard32 (ou pelo menos todo o final), ele não dá nem um erro,

acho que alguma coisa deve estar faltando, mas não faço a minima ideia de onde. :?

leonhard32

Se não ta inserindo nada e não lança nenhuma exception, vc deve ter esquecido de lançar ou imprimir exception em algum lugar, não?
Da uma olhada ai

celsocandiani

Seu arquivo hibernate.properties está na pasta src?

L

leonhard32,

era pra estar inserindo, na minha pagina tenho isto:

<p:inputText id=“inptNome” value="#{teste.pessoa.nome}"/>
<p:inputText id=“inptIdade” value="#{teste.pessoa.idade}"/>

ou seja ele passa la no managedBean (teste), passa pela classe pessoa e pega o nome/ idade;

<p:commandButton value=“CADASTRAR” action="#{teste.salvar}" process="@this, panelEdit" update=“panelView”/>
o botão tem o objeto salvar pra ir pro banco.

mas nada de dar certo! era pra estar inserindo, não era?

L

ta tudo ai certinho :!:

L

Permaneço sem conseguir insertar as informações no banco pessoal, e não sei mais o que fazer :?

o console apenas dá este aviso:

Lembrando que o hibernate chega a criar a tabela, mas não inseri as informações,

obrigado pela ajuda galera!

fabiozanardi

Parece ser um problema de codificação com caracteres especiais,

você está trabalhando o backend e o banco todo com UTF-8? se não experimente mudar as configurações para UTF-8

Criado 10 de fevereiro de 2012
Ultima resposta 13 de fev. de 2012
Respostas 13
Participantes 5