初始SessionFactory创建失败:org.hibernate.MappingException:配置无效

时间:2017-05-20 00:52:25

标签: java mysql hibernate

解决

这个问题是关于java hibernate。

当我运行Main类时,我收到此错误

Initial SessionFactory creation failed: org.hibernate.MappingException: 
invalid configuration
Exception in thread "main" java.lang.NullPointerException
at principal.ClienteDAO.guardaCliente(ClienteDAO.java:38)
at principal.Main.main(Main.java:31)
C:\Users\Nico\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 2 seconds)

不知道为什么我会得到那个例外

我的hibernate.cfg.xml是

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-configuration>
<session-factory>
    <!--TODA LA INFORMACION FUE SACADA DE: http://www.javatutoriales.com/2009/05/hibernate-parte-1-persistiendo-objetos.html-->

    <!-- parametros para la conexion a la base de datos -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/basededatosprueba</property>
    <property name="connection.username">root</property>
    <property name="connection.password"></property>

    <!-- Configuracion del pool interno -->
    <property name="connection.pool_size">1</property>

    <!-- Dialecto de la base de datos -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <!-- Otras propiedades importantes -->
    <property name="show_sql">true</property> 
    <property name="hbm2ddl.auto">create-drop</property>

    <!-- Archivos de mapeo -->
    <mapping resource="mapeos/Cliente.hbm.xml"/>
</session-factory>
</hibernate-configuration>

我的HibernateUtil类是

public class HibernateUtil {

private static SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory()
{
  try
  {
     if (sessionFactory == null)
     {
        Configuration configuration = new Configuration().configure(HibernateUtil.class.getResource("/hibernate.cfg.xml"));
        StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
        serviceRegistryBuilder.applySettings(configuration.getProperties());
        ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
     }
     return sessionFactory;
  } catch (Throwable ex)
  {
     System.err.println("Initial SessionFactory creation failed: " + ex);
     throw new ExceptionInInitializerError(ex);
  }
}

public static SessionFactory getSessionFactory()
{
  return sessionFactory;
 }


public static void shutdown()
{
  getSessionFactory().close();
}

我的ClassDAO

public class ClienteDAO {  
private Session sesion; 
private Transaction tx;  

public int guardaCliente(Cliente cliente) throws HibernateException 
{ 
    int id = 0;  

    try 
    { 
        iniciaOperacion(); 
        id = (int) sesion.save(cliente); 
        tx.commit(); 
    } catch (HibernateException he) 
    { 
        manejaExcepcion(he); 
        throw he; 
    } finally 
    { 
        sesion.close(); 
    }  

    return id; 
}  

public void actualizaCliente(Cliente cliente) throws HibernateException 
{ 
    try 
    { 
        iniciaOperacion(); 
        sesion.update(cliente); 
        tx.commit(); 
    } catch (HibernateException he) 
    { 
        manejaExcepcion(he); 
        throw he; 
    } finally 
    { 
        sesion.close(); 
    } 
}  

public void eliminaCliente (Cliente cliente) throws HibernateException 
{ 
    try 
    { 
        iniciaOperacion(); 
        sesion.delete(cliente); 
        tx.commit(); 
    } catch (HibernateException he) 
    { 
        manejaExcepcion(he); 
        throw he; 
    } finally 
    { 
        sesion.close(); 
    } 
}  

public Cliente obtenContacto(int codCliente) throws HibernateException 
{ 
   Cliente cliente = null;  
    try 
    { 
        iniciaOperacion(); 
        cliente = (Cliente) sesion.get(Cliente.class, codCliente); 
    } finally 
    { 
        sesion.close(); 
    }  

    return cliente; 
}  

public List<Cliente> obtenListaContactos() throws HibernateException 
{ 
    List<Cliente> listaContactos = null;  

    try 
    { 
        iniciaOperacion(); 
        listaContactos = sesion.createQuery("from Contacto").list(); 
    } finally 
    { 
        sesion.close(); 
    }  

    return listaContactos; 
}  

private void iniciaOperacion() throws HibernateException 
{ 
    sesion = HibernateUtil.getSessionFactory().openSession(); 
    tx = sesion.beginTransaction(); 
}  

private void manejaExcepcion(HibernateException he) throws HibernateException 
{ 
    tx.rollback(); 
    throw new HibernateException("Ocurrió un error en la capa de acceso a datos", he); 
} 
}

我试图运行

public static void main(String[] args) {

    int idAEliminar = 0;
    ClienteDAO clienteDAO = new ClienteDAO(); 
    Cliente contactoRecuperado;

    //Creamos tes instancias de Contacto  (String nombre, String direccion, int codigoPostal, String telefono, String cuit)
    Cliente cliente1 = new Cliente("Pedro", "dark 340", 3080, "86484","15531"); 
    Cliente cliente2 = new Cliente("Manuel", "orark 780", 5160, "86484","15531"); 
    Cliente cliente3 = new Cliente("Martin", "docrk 495", 3060, "86484","15531");  

    //Guardamos las tres instancias, guardamos el id del contacto1 para usarlo posteriormente 
    idAEliminar = clienteDAO.guardaCliente(cliente1); 
    clienteDAO.guardaCliente(cliente2);
    clienteDAO.guardaCliente(cliente3);

    //Modificamos el contacto 2 y lo actualizamos 
    cliente2.setNombre("Nuevo Contacto 2");
    clienteDAO.actualizaCliente(cliente2);

    //Recuperamos el contacto1 de la base de datos 
    contactoRecuperado = clienteDAO.obtenContacto(idAEliminar);
    System.out.println("Recuperamos a " + contactoRecuperado.getNombre());

    //Eliminamos al contactoRecuperado (que es el contacto3)
    clienteDAO.eliminaCliente(contactoRecuperado);

    //Obtenemos la lista de contactos que quedan en la base de datos y la mostramos
    List<Cliente> listaContactos = clienteDAO.obtenListaContactos();
    System.out.println("Hay " + listaContactos.size() + " clientes en la base de datos");

    for(Cliente c : listaContactos)
    {System.out.println("-> " + c.getNombre());
    } 
}

修改

我的Class.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="principal.Cliente" table="CLIENTE">
    <id name="codigo" column="codigo">
        <generator class="identity" />
    </id>
    <property name="nombre" type="string" column="nombre"/>
    <property name="direccion" type="string" column="direccion"/>
    <property name="telefono" type="string" column="telefono"/>
    <property name="cuit" type="string" column="cuit"/>
    <property name="codigoPostal" type="int" column="cp"/>
    <property name="saldo" type="double" column="saldo"/>
    <property name="deuda" type="double"  column="deuda"/> 
</class>
</hibernate-mapping>

编辑2: 所以,我不知道为什么,但我改变了 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>
    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/basededatosprueba</property>
    <property name="connection.username">root</property>
    <property name="connection.password"></property>
    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>
    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQL5Dialect</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.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">create</property>

    <mapping resource="mapeos/Cliente.hbm.xml"/>
</session-factory>
</hibernate-configuration>

解决了吗?我们会看到

1 个答案:

答案 0 :(得分:0)

我认为您可能需要关闭xml中的hibernate-configuration标记。