[RESOLVIDO]Hibernate apagando tabela

6 respostas
Cledsonjr

Bom tarde meu povo.

Estou com problema no Hibernate3.

Meu hibernate está apagando a table toda vez que subo ele.

<?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.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/matricula</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">123</property>
<property name="hibernate.hbm2dll.auto">update</property>  
<property name="show_sql ">true</property>  
</session-factory>
</hibernate-configuration>
Encontrei outro tópico aqui no forum, que foi orientado a usar
<property name="hibernate.hbm2dll.auto">update</property>
, coloquei no meu e mesmo assim não está funcionando.

Segue o restante das Classes:

Aluno.java
package br.com.matricula.modelo;

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

@Entity
public class Aluno {


	@Id
    @GeneratedValue
    private long id;
	private String nome;
	private String nomeMae;
	private String nomePai;
	private String dtNascimento;
	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 String getNomeMae() {
		return nomeMae;
	}
	public void setNomeMae(String nomeMae) {
		this.nomeMae = nomeMae;
	}
	public String getNomePai() {
		return nomePai;
	}
	public void setNomePai(String nomePai) {
		this.nomePai = nomePai;
	}

	public String getDtNascimento() {
		return dtNascimento;
	}
	public void setDtNascimento(String dtNascimento) {
		this.dtNascimento = dtNascimento;
	}
	public String getTelefone() {
		return telefone;
	}
	public void setTelefone(String telefone) {
		this.telefone = telefone;
	}
	
	
	
}

AlunoDaoImp.java

package br.com.matricula.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import util.HibernateUtil;
import br.com.matricula.modelo.Aluno;

public class AlunoDaoImp implements AlunoDao {

    public void save(Aluno aluno) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        session.save(aluno);
        t.commit();
    }
    public Aluno getAluno(long id) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        return (Aluno) session.load(Aluno.class, id);
    }
    public List<Aluno> list() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        List lista = session.createQuery("from Aluno").list();
        t.commit();
        return lista;
    }
    public void remove(Aluno aluno) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        session.delete(aluno);
        t.commit();
    }
    public void update(Aluno aluno) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        session.update(aluno);
        t.commit();
    }
}
AlunoControle.java
package br.com.matricula.controle;


import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.event.ActionEvent;

import br.com.matricula.dao.AlunoDao;
import br.com.matricula.dao.AlunoDaoImp;
import br.com.matricula.modelo.Aluno;

@ManagedBean//deverá ser usado alunoControle para acessar.
@RequestScoped
public class AlunoControle {

	private Aluno aluno;
	
	@javax.annotation.PostConstruct  
	public void inicializarObjetos(){  
	    this.aluno = new Aluno();
	} 
	
    public Aluno getAluno() {
		return aluno;
	}

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


	public void adicionarAluno(ActionEvent actionEvent){
    //   System.out.print("teste" + aluno.getNome() + aluno.getTelefone() + aluno.getDtNascimento()); 
		 AlunoDao dao = new AlunoDaoImp();
	     dao.save(aluno);
    }
}

HibernateUtil.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;


import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

import br.com.matricula.modelo.Aluno;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author José Alexandre
 */
public class HibernateUtil {

    private static SessionFactory sessionFactory;

    private HibernateUtil() {
        
    }

    public static SessionFactory getSessionFactory() {

        if (sessionFactory == null) {
            try {
                // Create the SessionFactory from standard (hibernate.cfg.xml)
                // config file.
                AnnotationConfiguration ac = new AnnotationConfiguration();
                ac.addAnnotatedClass(Aluno.class);
                sessionFactory = ac.configure().buildSessionFactory();
                SchemaExport se = new SchemaExport(ac);//retirar
               se.create(true, true);//retirar
                

            } catch (Throwable ex) {
                // Log the exception.
                System.err.println("Initial SessionFactory creation failed." + ex);
                throw new ExceptionInInitializerError(ex);
            }

            return sessionFactory;

        } else {
            return sessionFactory;
        }
        
    }

    public static void main(String[] args) {
        HibernateUtil.getSessionFactory();
    }

}
Mensagem
19/07/2012 16:23:20 org.hibernate.cfg.annotations.Version <clinit>
INFO: Hibernate Annotations 3.3.1.GA
19/07/2012 16:23:20 org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.2.5
19/07/2012 16:23:20 org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
19/07/2012 16:23:20 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
19/07/2012 16:23:20 org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
19/07/2012 16:23:20 org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
19/07/2012 16:23:20 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
19/07/2012 16:23:20 org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
19/07/2012 16:23:20 org.hibernate.cfg.AnnotationBinder bindClass
INFO: Binding entity from annotated class: br.com.matricula.modelo.Aluno
19/07/2012 16:23:20 org.hibernate.cfg.annotations.EntityBinder bindTable
INFO: Bind entity br.com.matricula.modelo.Aluno on table Aluno
19/07/2012 16:23:20 org.hibernate.cfg.AnnotationConfiguration secondPassCompile
INFO: Hibernate Validator not found: ignoring
19/07/2012 16:23:20 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Using Hibernate built-in connection pool (not for production use!)
19/07/2012 16:23:20 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Hibernate connection pool size: 20
19/07/2012 16:23:20 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: autocommit mode: false
19/07/2012 16:23:20 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: using driver: org.postgresql.Driver at URL: jdbc:postgresql://localhost:5432/matricula
19/07/2012 16:23:20 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: connection properties: {user=postgres, password=****}
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: RDBMS: PostgreSQL, version: 8.4.12
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC driver: PostgreSQL Native Driver, version: PostgreSQL 8.4 JDBC4 (build 702)
19/07/2012 16:23:20 org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.PostgreSQLDialect
19/07/2012 16:23:20 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
19/07/2012 16:23:20 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch size: 15
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch updates for versioned data: disabled
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: enabled
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): enabled
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Connection release mode: auto
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL inserts for batching: disabled
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
19/07/2012 16:23:20 org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>
INFO: Using ASTQueryTranslatorFactory
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JPA-QL strict compliance: disabled
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: disabled
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory createCacheProvider
INFO: Cache provider: org.hibernate.cache.NoCacheProvider
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Optimize cache for minimal puts: disabled
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Structured second-level cache entries: disabled
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Statistics: disabled
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Deleted entity synthetic identifier rollback: disabled
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default entity-mode: pojo
19/07/2012 16:23:20 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Named query checking : enabled
19/07/2012 16:23:20 org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
19/07/2012 16:23:21 org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured
19/07/2012 16:23:21 org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.PostgreSQLDialect
19/07/2012 16:23:21 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: Running hbm2ddl schema export
19/07/2012 16:23:21 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: exporting generated schema to database
19/07/2012 16:23:21 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Using Hibernate built-in connection pool (not for production use!)
19/07/2012 16:23:21 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Hibernate connection pool size: 20
19/07/2012 16:23:21 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: autocommit mode: false
19/07/2012 16:23:21 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: using driver: org.postgresql.Driver at URL: jdbc:postgresql://localhost:5432/matricula
19/07/2012 16:23:21 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: connection properties: {user=postgres, password=****}
drop table Aluno
drop sequence hibernate_sequence
create table Aluno (id int8 not null, dtNascimento varchar(255), nome varchar(255), nomeMae varchar(255), nomePai varchar(255), telefone varchar(255), primary key (id))
create sequence hibernate_sequence
19/07/2012 16:23:21 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: schema export complete
19/07/2012 16:23:21 org.hibernate.connection.DriverManagerConnectionProvider close
INFO: cleaning up connection pool: jdbc:postgresql://localhost:5432/matricula

Aguardo a ajuda de voces.
Desde de já agradeço.

6 Respostas

Hebert_Coelho

E sobre essas duas linhas no seu código?

SchemaExport se = new SchemaExport(ac);//retirar
se.create(true, true);//retirar

CristianPalmaSola10

Poste seu hibernate.cfg.xml completo

o que eu imagino que esteja acontecendo é o seguindo, voce esqueceu de colocar a classe da tabela em questao no seu hibernate.cfg.xml e quando voce fez schema export.create(true, true) alem de criar o sql para criação da base de dados voce mandou o hibernate executar o sql apagando a tabela, eu sugiro tira o export schema e colocar a classe no hibernate.cfg.xml

Cledsonjr

Caro jakefrog desculpa fazê-lo perder tempo. Não faço idéia de onde saiu isso. Olhei antes e não vi nada. Hibernate mais eu temos uma briga eu querendo aprender ele e ele não querendo que eu aprenda.hehe
Mas provavelmente logo estarei postando mais dúvidas, na próxima irei prestar mais atenção.

Cledsonjr

CristianPalmaSola10:
Poste seu hibernate.cfg.xml completo

o que eu imagino que esteja acontecendo é o seguindo, voce esqueceu de colocar a classe da tabela em questao no seu hibernate.cfg.xml e quando voce fez schema export.create(true, true) alem de criar o sql para criação da base de dados voce mandou o hibernate executar o sql apagando a tabela, eu sugiro tira o export schema e colocar a classe no hibernate.cfg.xml

Vlw CristianPalmaSola10, mas foi falta de atenção minha. Havia colocado SchemaExport se = new SchemaExport(ac);//retirar se.create(true, true);//retirar , só retirei e começou a funcionar.

Obrigado pela atenção.

Hebert_Coelho

Cledsonjr:
Caro jakefrog desculpa fazê-lo perder tempo. Não faço idéia de onde saiu isso. Olhei antes e não vi nada. Hibernate mais eu temos uma briga eu querendo aprender ele e ele não querendo que eu aprenda.hehe
Mas provavelmente logo estarei postando mais dúvidas, na próxima irei prestar mais atenção.
Esquenta não mano. Acontece com todos. =D

drsmachado

Cledsonjr:
Caro jakefrog desculpa fazê-lo perder tempo. Não faço idéia de onde saiu isso. Olhei antes e não vi nada. Hibernate mais eu temos uma briga eu querendo aprender ele e ele não querendo que eu aprenda.hehe
Mas provavelmente logo estarei postando mais dúvidas, na próxima irei prestar mais atenção.

O Hibernate é meio temperamental.
Mas, em todo caso, um debug faz muito sucesso nessas horas.

Criado 19 de julho de 2012
Ultima resposta 19 de jul. de 2012
Respostas 6
Participantes 4