Que exception? posta o erro ai.
Re:hibernate não salva objeto
7 Respostas
Voce tem um campo @Id na tabela Aluno?
Pode postar a classe Aluno, o arquivo de configuração do Hibernate, e o StackTrace da Exception?
Só salva o primeiro?
Tenta fazer isso.
Transaction t = session.beginTransaction();
session.save(new Aluno());
session.save(new Aluno());
t.commit();
E olhe no banco.
PS: os dois new Aluno é apenas para criar com Ids diferentes.
PS2:Poste seu código ente as tags [code] e [ /code]
Tem certeza que isso é assim mesmo:
<generator class = "increment" />
Não é auto-incremente ?
Eu não sei nada sobre os arquivos .hbm.xml, eu uso apenas o Hibernate Annotations que é muito mais fáçil.
estou fazendo meu primeiro teste no Hibernate e nao consigo salvar meu objeto, ta caindo na Exception. Se alguem puder ajudar eu agradeço.
public static void main(String args[]){
Aluno aluno = new Aluno();
aluno.setNome("david");
aluno.setCpf("123");
try {
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
Transaction transaction = (Transaction) session.beginTransaction();
session.save(aluno);
session.close();
transaction.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
consegui tirar o erro, porem o hibernate so salva o primeiro objeto, aparti do segundo nao da nem execeção, simplesmente nao salva, nao tenho nem ideia o que seja.
Main corrigido
public class TesteMain {
public static void main(String args[]) {
Aluno aluno = new Aluno();
aluno.setNome("david augusto");
aluno.setCpf("123");
try {
SessionFactory factory = new Configuration().configure()
.buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
session.save(aluno);
session.flush();
session.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("erro no void");
}
}
}
Hibernate.cfg.xml
<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/testehibernate
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<!-- Condiguração do c3p0 -->
<property name="hibernate.c3p0.max_size">10</property>
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.c3p0.max_statements">10</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<!-- Configurações de debug -->
<property name="show_sql">true</property>
<property name="use_outer_join">true</property>
<property name="hibernate.generate_statistics">true</property>
<property name="hibernate.use_sql_comments">true</property>
<mapping resource="Aluno.hbm.xml" />
</session-factory>
Aluno.hbm.xml
<?xml version="1.0" encoding="UTF-8"?><class name="Aluno" table="aluno">
<!-- Identificador da classe -->
<id name="idAluno" type="int">
<generator class="increment" />
</id>
<!-- Propriedades da classe -->
<property name="nome" column="nome" type="string"/>
<property name="cpf" column="cpf" type="string"/>
</class>
classe aluno
public class Aluno {
private int idAluno;
private String nome;
private String cpf;
public Aluno(){
}
//get e setters
}
Ele salvou o primeiro registro, dai eu fui no banco e exclui o objeto e tentei salvar de novo, e por incrivel que pareça nao consegui salvar, voltou a estaca zero, vou postar o que saiu no console, pra ver se alguem tem alguma ideia, desde ja agradeço a ajuda.
console
DEBUG HbmBinder:1267 - Mapped property: idAluno -> idAluno
DEBUG HbmBinder:1267 - Mapped property: nome -> nome
DEBUG HbmBinder:1267 - Mapped property: cpf -> cpf
INFO Configuration:1547 - Configured SessionFactory: null //era pra ta vindo null?
AbstractBatcher:484 - preparing statement
IncrementGenerator:95 - first free id: 1
DEBUG AbstractBatcher:374 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
DEBUG AbstractBatcher:533 - closing statement
DEBUG AbstractSaveEventListener:112 - generated identifier: 1, using strategy: org.hibernate.id.IncrementGenerator
DEBUG AbstractSaveEventListener:153 - saving [Aluno#1]
DEBUG AbstractFlushingEventListener:58 - flushing session
DEBUG AbstractFlushingEventListener:111 - processing flush-time cascades
DEBUG AbstractFlushingEventListener:154 - dirty checking collections
DEBUG AbstractFlushingEventListener:171 - Flushing entities and processing referenced collections
DEBUG AbstractFlushingEventListener:210 - Processing unreferenced collections
DEBUG AbstractFlushingEventListener:224 - Scheduling collection removes/(re)creates/updates
DEBUG AbstractFlushingEventListener:85 - Flushed: 1 insertions, 0 updates, 0 deletions to 1 objects
DEBUG AbstractFlushingEventListener:91 - Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
DEBUG Printer:83 - listing entities:
DEBUG Printer:90 - Aluno{nome=david augusto, cpf=123, idAluno=1}
DEBUG AbstractFlushingEventListener:290 - executing flush
DEBUG ConnectionManager:469 - registering flush begin
DEBUG AbstractEntityPersister:2209 - Inserting entity: [Aluno#1]
DEBUG AbstractBatcher:366 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
DEBUG SQL:401 - /* insert Aluno */ insert into aluno (nome, cpf, idAluno) values (?, ?, ?)
Hibernate: /* insert Aluno */ insert into aluno (nome, cpf, idAluno) values (?, ?, ?)
DEBUG AbstractBatcher:484 - preparing statement
DEBUG AbstractEntityPersister:1997 - Dehydrating entity: [Aluno#1]
DEBUG AbstractBatcher:44 - Executing batch size: 1
DEBUG AbstractBatcher:374 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
DEBUG AbstractBatcher:533 - closing statement
DEBUG ConnectionManager:478 - registering flush end
DEBUG AbstractFlushingEventListener:321 - post flush
DEBUG SessionImpl:273 - closing session
DEBUG ConnectionManager:380 - performing cleanup
DEBUG ConnectionManager:441 - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
finalmente problema resolvido.
o problema era que eu nao estava usando o commit. Cinco dias tentando salvar um objeto, e como sempre a solucao estava no guj, valeu pessoal.
public static void main(String args[]) {
Aluno aluno = new Aluno();
aluno.setNome("David Augusto");
aluno.setCpf("2873");
try {
Session sessao = factory.openSession();
Transaction tx = sessao.beginTransaction();
sessao.save(aluno);
sessao.flush();
tx.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("erro no void");
}
}