Properly configured hibernate does not insert into database

Asked

Viewed 942 times

6

My code does not enter in the database Mysql. It identifies all database, tables and fields, but insertion is not done.

Usuariodao.java

package br.com.sistec.dao;

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

import br.com.sistec.domain.Usuario;
import br.com.sistec.util.HibernateUtil;

public class UsuarioDAO {


    public void salvar(Usuario usuario){

        Session sessao = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = null;

        try{

            transacao = sessao.beginTransaction();
            sessao.save(usuario);
            transacao.commit();


        }catch (Exception ex){
            if(transacao != null){

                transacao.rollback();

            }


        }

            finally{

                sessao.close();
            }
        }



    }

Hibernateutil.java

package br.com.sistec.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {

            Configuration configuration = new Configuration();
            configuration.configure();

            ServiceRegistry serviceregistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();

            SessionFactory sessionFactory = configuration
                    .buildSessionFactory(serviceregistry);

            return sessionFactory;

        }

        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

Java user.

package br.com.sistec.domain;

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

@Entity
@Table(name ="tbl_usuario")
public class Usuario {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "cpo_usuid")
    private Long codigo;

    @Column(name = "cpo_usuusuario", length = 40, nullable = false)
    private String usuario;

    @Column(name = "cpo_ususenha", length = 10, nullable = false)
    private String senha;

    public Long getCodigo() {
        return codigo;
    }

    public void setCodigo(Long codigo) {
        this.codigo = codigo;
    }

    public String getUsuario() {
        return usuario;
    }

    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

Usuariodaotest.java

package br.com.sistec.test;

import org.junit.Test;

import br.com.sistec.dao.UsuarioDAO;
import br.com.sistec.domain.Usuario;

public class UsuarioDAOTest {

        @Test
        public void salvar(){

            Usuario u1 = new Usuario();
            u1.setUsuario("Teste");


            Usuario u2 = new Usuario();
            u2.setUsuario("Teste");


            UsuarioDAO usuDao = new UsuarioDAO();

            usuDao.salvar(u1);
            usuDao.salvar(u2);


    }


}

Hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/db_sistec</property>
        <property name="connection.username">root</property>
        <property name="connection.password">fatec</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">validate</property>


        <mapping class="br.com.sistec.domain.Usuario"/>


    </session-factory>

</hibernate-configuration>

Somebody help me?

  • Have you tried debugging? He gets into the catch of Save?

  • has not released any Exception, correct? just does not persist?

  • that even it does not launch any Exception, Junit informs that the save method is correct and everything turns green, it identifies the tables all but the insertion is not done.

  • 1

    Is any INSERT SQL shown in the application console? Or just view Selects?

2 answers

4


Well, come on:

  1. The mistake isn’t coming because you’re doing nothing with the exception, try to put a ex.printStackTrace(); in its saving method which is in the DAO that you will find the error.
  2. The problem is very simple, in the model you put the following property in password attribute: @Column(name = "cpo_ususenha",length = 10, nullable = false). I mean, you’re saying that this attribute cannot be null. Note that you cannot passes a value to him in his Test.

To solve the Voce problem you can map this attribute as nullable = true or else pass a value to him, ex:

u1.setSenha("senha1");

-3

import br.com.sistec.domain.Usuario;
import br.com.sistec.util.HibernateUtil;

public class UsuarioDAO {

 private  Session sessao;

 private Transaction transacao = null;

  public UsuarioDAO(){
        sessao = HibernateUtil.getSessionFactory().openSession();
  }  

    public void salvar(Usuario usuario){


        try{

            transacao = sessao.beginTransaction();
            sessao.save(usuario);
            transacao.commit();


        }catch (Exception ex){
            if(transacao != null){

                transacao.rollback();

            }


        }

            finally{

                sessao.close();
            }
        }



    }

Another option for your Unit Test.

package br.com.sistec.test;

import org.junit.Test;

import br.com.sistec.dao.UsuarioDAO;
import br.com.sistec.domain.Usuario;

public class UsuarioDAOTest {

        @Test
        public void salvar(){

        try{

           Session sessao = HibernateUtil.getSessionFactory().openSession();

           Transaction transacao = sessao.beginTransaction();

           Usuario u1 = new Usuario();

           u1.setUsuario("Teste");


            Usuario u2 = new Usuario();
            u2.setUsuario("Teste");

            sessao.save(u1);
            sessao.save(u2);

            transacao.commit();

          } catch(Exception e){

             e.printStackTrace();

           }

    }
  • 3

    Hello Mark. What is your code doing different from OP code? (Besides moving the session and transaction to class scope)? How this piece of code answers the OP question?

  • 1

    That only he can answer.

  • 4

    @Mark does not understand, how only "he" can answer? What Anthony wants to know is in what your answer solves the problem? How did you come to this solution? Why would this possibly solve the problem? I recommend reading this FAQ link: http://answall.com/help/how-to-answer Being brief is acceptable, but more thorough explanations are better. (it wasn’t me who denied your answer, but if you edit it and leave it more complete I give you +1 to give up ;) - I hope you understand all this as a constructive criticism!

  • 3

    Thank you for your suggestion. Constructive criticism is always welcome !!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.