Hibernate não esta gerando as tabelas

4 respostas
Jr_webmaster_100_jav

Estou trabalhando em uma aplicação web com Struts + hibernate.
mas quando eu executo a minha action que insere no banco ( o banco existe mas a tabela nao ) ele diz que a tabela não existe.
isso faria sentido se o hiberate nao gerasse automaticamente as tabelas ( ou estou enganado ? )
Veja meus códigos.

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="hibernate.dialect">
			org.hibernate.dialect.MySQLDialect
		</property>
		<property name="hibernate.connection.driver_class">
		   com.mysql.jdbc.Driver
		</property>
		<property name="hibernate.connection.url">
		    jdbc:mysql://localhost:3306/docmanager
		</property>
		<property name="hibernate.connection.username">
		    root
		</property>
		<property name="hibernate.connection.password">
		
		</property>
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.hbm2dll.auto">update</property>
		<mapping resource="/mapeamentos/usuario.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

Usuario.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="br.com.rjsistemas.docmanager.bean">
	<class name="Usuario" table="usuarios">
		<id name="_codigo" column="id" type="int">
			<generator class="increment"/>
		</id>
		<property name="_nome" column="nome" not-null="true" length="50" type="java.lang.String"/>
		<property name="_login" column="login" not-null="true" length="30" type="java.lang.String"/>
		<property name="_senha" column="senha" not-null="true" length="15" type="java.lang.String"/>
		<property name="_email" column="email" not-null="true" length="100" type="java.lang.String"/>
		<property name="_perguntaSecreta" column="perguntaSecreta" not-null="true" length="150" type="java.lang.String"/>
		<property name="_respostaSecreta" column="respostaSecreta" not-null="true" length="100" type="java.lang.String"/>	
	</class>    
</hibernate-mapping>

Minha Action

package br.com.rjsistemas.docmanager.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import br.com.rjsistemas.docmanager.bean.Usuario;
import br.com.rjsistemas.docmanager.controller.UsuarioController;

public class UsuarioInsertAction extends Action{

@Override
public ActionForward execute(ActionMapping arg0, ActionForm form,
		HttpServletRequest request, HttpServletResponse response)
		throws Exception {
	

	Usuario usu = (Usuario)form;
	UsuarioController controller = new UsuarioController();
	
	if(controller.addUsuario(usu.get_nome(), usu.get_email(), 
			usu.get_login(), usu.get_senha(),
			usu.get_perguntaSecreta(),usu.get_respostaSecreta()))
	{
		return arg0.findForward("success");
	}else
	{
		return arg0.findForward("failed");
	}
	
	
	
}	
	
	
}

Meu controller

package br.com.rjsistemas.docmanager.controller;

import java.util.List;

import br.com.rjsistemas.docmanager.bean.Usuario;
import br.com.rjsistemas.docmanager.dao.UsuarioDAO;

public class UsuarioController {

	public boolean addUsuario(String nome,String email, String login, String senha, String perguntaSecreta, String respostaSecreta)
	{
		UsuarioDAO dao = new UsuarioDAO();
		Usuario usu = new Usuario();
		usu.set_nome(nome);
		usu.set_email(email);
		usu.set_login(login);
		usu.set_senha(senha);
		usu.set_perguntaSecreta(perguntaSecreta);
		usu.set_respostaSecreta(respostaSecreta);
		return dao.inserir(usu);
	}
	
	public boolean editUsuario(int id,String nome,String email, String login, String senha, String perguntaSecreta, String respostaSecreta)
	{
		UsuarioDAO dao = new UsuarioDAO();
		Usuario usu = new Usuario();
		usu.set_codigo(id);
		usu.set_nome(nome);
		usu.set_email(email);
		usu.set_login(login);
		usu.set_senha(senha);
		usu.set_perguntaSecreta(perguntaSecreta);
		usu.set_respostaSecreta(respostaSecreta);
		return dao.atualizar(usu);
	}
	
	public boolean deleteUsuario(int id)
	{
		UsuarioDAO dao = new UsuarioDAO();
		Usuario usu = dao.selecionaPorCodigo(id);
		return dao.deletar(usu);
	}
	
	public List<Usuario> getAllUsuario()
	{
		
		UsuarioDAO dao = new UsuarioDAO();
		return dao.selecionaTudo();
	}
	
	public Usuario getUsuarioById(int id)
	{
		UsuarioDAO dao = new UsuarioDAO();
		return dao.selecionaPorCodigo(id);
	}
	
	public Usuario efetuaLogin(String login, String senha)
	{
		UsuarioDAO dao = new UsuarioDAO();
		return dao.selecionaPorLogin(login, senha);
	}
}

Meu DAO

package br.com.rjsistemas.docmanager.dao;
import java.util.List;

import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.criterion.Restrictions;

import br.com.rjsistemas.docmanager.bean.Usuario;

public class UsuarioDAO {

	
	public UsuarioDAO() {
		// TODO Auto-generated constructor stub
	}
	
	public boolean inserir(Usuario usu)
	{
	  SessionFactory fabrica = new Configuration().
	  								   configure().
	  					     buildSessionFactory();
	  Session sessao = fabrica.openSession();
	  	try
	  		{
	  			Transaction transacao = sessao.beginTransaction();
	  			sessao.save (usu);
	  			transacao.commit();
	  			return true;
	  		}
	  	catch(HibernateException ex)
	  		{
	  			return false;
	  		}
	  	finally
	  		{
	  			sessao.close();
	  		}
	 
	 
	}
	
	public boolean atualizar(Usuario usu)
	{
	  SessionFactory fabrica = new Configuration().
	  								   configure().
	  					     buildSessionFactory();
	  Session sessao = fabrica.openSession();
	  try
		{
			Transaction transacao = sessao.beginTransaction();
			sessao.update(usu);
			transacao.commit();
			return true;
		}
	catch(HibernateException ex)
		{
			return false;
		}
	finally
		{
			sessao.close();
		}
	 
	}
	
	public boolean deletar(Usuario usu)
	{
	  SessionFactory fabrica = new Configuration().
	  								   configure().
	  					     buildSessionFactory();
	  Session sessao = fabrica.openSession();
	  try
		{
			Transaction transacao = sessao.beginTransaction();
			sessao.delete(usu);
			transacao.commit();
			return true;
		}
	catch(HibernateException ex)
		{
			return false;
		}
	finally
		{
			sessao.close();
		}
	 
	}
	
	
	@SuppressWarnings("unchecked")
	public List<Usuario> selecionaTudo()
	{
		SessionFactory fabrica = new Configuration().
		   configure().
           buildSessionFactory();
           Session sessao = fabrica.openSession();
        return sessao.createCriteria(Usuario.class).list();
		
	}
	
	public Usuario selecionaPorCodigo(int codigo)
	{
		SessionFactory fabrica = new Configuration().
		   configure().
           buildSessionFactory();
           Session sessao = fabrica.openSession();
           return (Usuario)sessao.createCriteria(Usuario.class).add(Restrictions.eq("codigo", codigo)).uniqueResult();
		
	}
	
	public Usuario selecionaPorLogin(String login, String senha)
	{
		SessionFactory fabrica = new Configuration().
		   configure().
           buildSessionFactory();
           Session sessao = fabrica.openSession();
           return (Usuario)sessao.createCriteria(Usuario.class).
           add(Restrictions.eq("login", login).ignoreCase()).
           add(Restrictions.eq("senha", senha).ignoreCase()).
           uniqueResult();
		
	}
	
	
	
	
}

quando eu rodo. ele executa a aplcação web (struts) sossegado, mas da o seguinte erro:

Fev 22, 2012 2:29:35 PM org.apache.catalina.core.AprLifecycleListener init

INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files (x86)\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files (x86)/Java/jre7/bin/client;C:/Program Files (x86)/Java/jre7/bin;C:\Program Files (x86)\CollabNet;C:\Program Files (x86)\Embarcadero\RAD Studio\9.0\bin;C:\Users\Public\Documents\RAD Studio\9.0\Bpl;C:\Program Files (x86)\Embarcadero\RAD Studio\9.0\bin64;C:\Users\Public\Documents\RAD Studio\9.0\Bpl\Win64;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Program Files (x86)\Microsoft SQL Server\90\Tools\binn;C:\Program Files (x86)\QuickTime\QTSystem;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn;C:\Program Files\Microsoft SQL Server\100\Tools\Binn;C:\Program Files\Microsoft SQL Server\100\DTS\Binn;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE;C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn;C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies;.

Fev 22, 2012 2:29:35 PM org.apache.tomcat.util.digester.SetPropertiesRule begin

WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property source to org.eclipse.jst.jee.server:DocManager did not find a matching property.

Fev 22, 2012 2:29:35 PM org.apache.coyote.http11.Http11Protocol init

INFO: Initializing Coyote HTTP/1.1 on http-8080

Fev 22, 2012 2:29:35 PM org.apache.catalina.startup.Catalina load

INFO: Initialization processed in 557 ms

Fev 22, 2012 2:29:36 PM org.apache.catalina.core.StandardService start

INFO: Starting service Catalina

Fev 22, 2012 2:29:36 PM org.apache.catalina.core.StandardEngine start

INFO: Starting Servlet Engine: Apache Tomcat/6.0.33

Fev 22, 2012 2:29:36 PM org.apache.struts.action.ActionServlet initChain

INFO: Loading chain catalog from jar:file:/C:/Users/junior/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/DocManager/WEB-INF/lib/struts-core-1.3.10.jar!/org/apache/struts/chain/chain-config.xml

Fev 22, 2012 2:29:36 PM org.apache.coyote.http11.Http11Protocol start

INFO: Starting Coyote HTTP/1.1 on http-8080

Fev 22, 2012 2:29:36 PM org.apache.jk.common.ChannelSocket init

INFO: JK: ajp13 listening on /0.0.0.0:8009

Fev 22, 2012 2:29:36 PM org.apache.jk.server.JkMain start

INFO: Jk running ID=0 time=0/31  config=null

Fev 22, 2012 2:29:36 PM org.apache.catalina.startup.Catalina start

INFO: Server startup in 815 ms

Fev 22, 2012 2:29:36 PM org.apache.struts.chain.ComposableRequestProcessor init

INFO: Initializing composable request processor for module prefix ''

Fev 22, 2012 2:29:36 PM org.apache.struts.chain.commands.servlet.CreateAction createAction

INFO: Initialize action of type: br.com.rjsistemas.docmanager.action.BemVindoAction

Fev 22, 2012 2:29:41 PM org.apache.struts.chain.commands.servlet.CreateAction createAction

INFO: Initialize action of type: br.com.rjsistemas.docmanager.action.UsuarioInsertAction

11 [http-8080-2] INFO org.hibernate.cfg.Environment - Hibernate <a href="http://3.3.2.GA">3.3.2.GA</a>

13 [http-8080-2] INFO org.hibernate.cfg.Environment - hibernate.properties not found

16 [http-8080-2] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist

19 [http-8080-2] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling

159 [http-8080-2] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml

159 [http-8080-2] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml

216 [http-8080-2] INFO org.hibernate.cfg.Configuration - Reading mappings from resource : /mapeamentos/usuario.hbm.xml

281 [http-8080-2] INFO org.hibernate.cfg.HbmBinder - Mapping class: br.com.rjsistemas.docmanager.bean.Usuario -> usuarios

294 [http-8080-2] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null

354 [http-8080-2] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)

354 [http-8080-2] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20

354 [http-8080-2] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false

360 [http-8080-2] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/docManager

360 [http-8080-2] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=root, password=****}

579 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - RDBMS: MySQL, version: 5.5.8-log

579 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.13 ( Revision: ${bzr.revision-id} )

606 [http-8080-2] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQLDialect

610 [http-8080-2] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions)

611 [http-8080-2] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)

612 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled

612 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled

612 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15

612 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled

612 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled

612 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled

612 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto

613 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2

613 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1

613 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled

613 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled

613 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled

613 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory

622 [http-8080-2] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory

622 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {}

622 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled

622 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled

622 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled

622 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory

622 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled

622 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled

627 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled

627 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled

627 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo

627 [http-8080-2] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled

669 [http-8080-2] INFO org.hibernate.impl.SessionFactoryImpl - building session factory

749 [http-8080-2] ERROR org.hibernate.tuple.entity.PojoEntityTuplizer - Getters of lazy classes cannot be final: br.com.rjsistemas.docmanager.bean.Usuario._nome

749 [http-8080-2] ERROR org.hibernate.tuple.entity.PojoEntityTuplizer - Setters of lazy classes cannot be final: br.com.rjsistemas.docmanager.bean.Usuario._nome

749 [http-8080-2] ERROR org.hibernate.tuple.entity.PojoEntityTuplizer - Getters of lazy classes cannot be final: br.com.rjsistemas.docmanager.bean.Usuario._login

749 [http-8080-2] ERROR org.hibernate.tuple.entity.PojoEntityTuplizer - Setters of lazy classes cannot be final: br.com.rjsistemas.docmanager.bean.Usuario._login

749 [http-8080-2] ERROR org.hibernate.tuple.entity.PojoEntityTuplizer - Getters of lazy classes cannot be final: br.com.rjsistemas.docmanager.bean.Usuario._senha

749 [http-8080-2] ERROR org.hibernate.tuple.entity.PojoEntityTuplizer - Setters of lazy classes cannot be final: br.com.rjsistemas.docmanager.bean.Usuario._senha

749 [http-8080-2] ERROR org.hibernate.tuple.entity.PojoEntityTuplizer - Getters of lazy classes cannot be final: br.com.rjsistemas.docmanager.bean.Usuario._email

749 [http-8080-2] ERROR org.hibernate.tuple.entity.PojoEntityTuplizer - Setters of lazy classes cannot be final: br.com.rjsistemas.docmanager.bean.Usuario._email

749 [http-8080-2] ERROR org.hibernate.tuple.entity.PojoEntityTuplizer - Getters of lazy classes cannot be final: br.com.rjsistemas.docmanager.bean.Usuario._perguntaSecreta

749 [http-8080-2] ERROR org.hibernate.tuple.entity.PojoEntityTuplizer - Setters of lazy classes cannot be final: br.com.rjsistemas.docmanager.bean.Usuario._perguntaSecreta

749 [http-8080-2] ERROR org.hibernate.tuple.entity.PojoEntityTuplizer - Getters of lazy classes cannot be final: br.com.rjsistemas.docmanager.bean.Usuario._respostaSecreta

749 [http-8080-2] ERROR org.hibernate.tuple.entity.PojoEntityTuplizer - Setters of lazy classes cannot be final: br.com.rjsistemas.docmanager.bean.Usuario._respostaSecreta

870 [http-8080-2] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured

940 [http-8080-2] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1146, SQLState: 42S02

940 [http-8080-2] ERROR org.hibernate.util.JDBCExceptionReporter - Table docmanager.usuarios doesnt exist

dizendo q nao existe a tabela… mas nao era pra criar ? o que estou fazendo errado ?
Agradeço a todos que puderem me ajudar.

4 Respostas

fbl.lucas

Tenta colocando isso:

<property name="hibernate.hbm2dll.auto">create</property>
drsmachado

fbl.lucas:
Tenta colocando isso:

<property name="hibernate.hbm2dll.auto">create</property>


Eu sugiro colocar isto, mas ao invés de create, usar update

Jr_webmaster_100_jav

essa propriedade é do hbm.xml ?

porque se for do hibernate.cfg.xml… ela ja se encontra la

Jr_webmaster_100_jav

consegui
mudei o

<property name="hibernate.hbm2dll.auto">update</property>

para

<property name="hibernate.hbm2ddl.auto">update</property>

Criado 22 de fevereiro de 2012
Ultima resposta 22 de fev. de 2012
Respostas 4
Participantes 3