Hibernate correctly configured does not insert into the database

5

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

UserID.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;
    }

}

User.java

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;
    }

UsernameDAest.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>

Does anyone help me?

    
asked by anonymous 27.06.2015 / 23:13

2 answers

3

Well, come on:

  • The error is not appearing because you are not doing anything with exception , try to put a ex.printStackTrace(); in your save method that is in DAO you will find the error.
  • The problem is very simple, in the model you put the following property in the password attribute: @Column(name = "cpo_ususenha",length = 10, nullable = false) . That is, you are saying that this attribute can not be null. Note that you do not passes a value to it in your Test.
  • To solve the problem, you can map this attribute to nullable = true or pass a value to it, eg:

    u1.setSenha("senha1");
    
        
    04.12.2015 / 16:28
    -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();
    
               }
    
        }
    
        
    04.12.2015 / 14:27