0

I'm new in Hibernate and I'm trying to create a little aplication in Java using Maven in IntelliJ Idea. I'm having this error in title above, and answers of the same problem here on Stack did not helped me until now.

What is this file "Person.hbm.xml". I have to create it? Once it is a mapping resource, Hibernate should not create it itself?

I'm getting this error when I run my little program:

Exception in thread "main" org.hibernate.boot.MappingNotFoundException: Mapping (RESOURCE) not found : HibernateExposed/Person.hbm.xml : origin(HibernateExposed/Person.hbm.xml)
    at org.hibernate.boot.spi.XmlMappingBinderAccess.bind(XmlMappingBinderAccess.java:56)
    at org.hibernate.boot.MetadataSources.addResource(MetadataSources.java:274)
    at org.hibernate.boot.cfgxml.spi.MappingReference.apply(MappingReference.java:70)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:412)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:86)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
    at Persistencia.HibernateUtils.<init>(HibernateUtils.java:10)
    at Main.Main.main(Main.java:16)

This is my class of database configuration: HibernateUtils:

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {

    //Fábrica de sessões de banco de dados constante no padrão SINGLETON

    SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

}

And bellow, my entity class that I'm trying to persist:

import javax.persistence.Entity;
import java.sql.Date;

@Entity
public class Produto {


    private String nome;
    private int cod;
    private float valor;
    private Date dataValidade;

    protected Produto() {
    }

    public Produto(String nome, int cod, float valor, Date dataValidade) {
        this.nome = nome;
        this.cod = cod;
        this.valor = valor;
        this.dataValidade = dataValidade;
    }



    /*public Produto getProdutoPorNome(String nome) {

        Produto buscaResult  = //Resultado da busca.
    }
    */

    public boolean excluirProduto(int cod) {

        boolean deuCerto=false;

        return deuCerto;
    }
}

And my Main class:

package Main;

import Persistencia.HibernateUtils;
import ProcessoDeVenda.Produto;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import java.util.Date;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Session sessao;

        HibernateUtils hiber = new HibernateUtils();
        SessionFactory session = hiber.getSessionFactory();
        Produto produto;

        try {
            sessao = session.openSession();

            Date data = new Date(05, 12, 2018);
            float valor = (float) 42000.0;

            produto = new Produto("Carro", 1, valor, (java.sql.Date) data);

            System.out.println(produto.toString());

        }catch (Exception sqlException) {
            System.out.println(sqlException);
        }

    }

}

The project structure, with the location of hibernate.cfg.xml file.

enter image description here

And my hibernate.cfg.xml file content: Look at the "mapping resource" tag.

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:~/PDV</property>
        <property name="connection.username">Lucas</property>
        <property name="connection.password">mypass</property>

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

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.H2Dialect</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">update</property>

        <mapping resource="HibernateExposed/Person.hbm.xml" />

    </session-factory>

</hibernate-configuration>

Now, i'm trying to map classes direct on hibernate.cfg.xml. (Why hibernate does not make this itself? I'm using anotations...)

I've deleted

<mapping resource="HibernateExposed/Person.hbm.xml" />

ANd in i'ts place I've mapped the class:

   <mapping class="src.main.java.ProcessoDeVenda.Produto" />

And the error just changed to this:

Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:271)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:417)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:86)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
    at Persistencia.HibernateUtils.<init>(HibernateUtils.java:10)
    at Main.Main.main(Main.java:16)
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:105)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:123)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:41)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:58)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.addConnections(DriverManagerConnectionProviderImpl.java:363)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.<init>(DriverManagerConnectionProviderImpl.java:282)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.<init>(DriverManagerConnectionProviderImpl.java:260)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections$Builder.build(DriverManagerConnectionProviderImpl.java:401)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:112)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:75)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
    ... 15 more
Caused by: org.h2.jdbc.JdbcSQLException: Database may be already in use: null. Possible solutions: close all other connection(s); use the server mode [90020-197]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
    at org.h2.message.DbException.get(DbException.java:168)
    at org.h2.mvstore.db.MVTableEngine$Store.convertIllegalStateException(MVTableEngine.java:188)
    at org.h2.mvstore.db.MVTableEngine$Store.open(MVTableEngine.java:168)
    at org.h2.mvstore.db.MVTableEngine.init(MVTableEngine.java:100)
    at org.h2.engine.Database.getPageStore(Database.java:2538)
    at org.h2.engine.Database.open(Database.java:709)
    at org.h2.engine.Database.openDatabase(Database.java:286)
    at org.h2.engine.Database.<init>(Database.java:280)
    at org.h2.engine.Engine.openSession(Engine.java:66)
    at org.h2.engine.Engine.openSession(Engine.java:179)
    at org.h2.engine.Engine.createSessionAndValidate(Engine.java:157)
    at org.h2.engine.Engine.createSession(Engine.java:140)
    at org.h2.engine.Engine.createSession(Engine.java:28)
    at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:351)
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:124)
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:103)
    at org.h2.Driver.connect(Driver.java:69)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
    ... 30 more
Caused by: java.lang.IllegalStateException: The file is locked: nio:C:/Users/Lucas_Pletsch/PDV.mv.db [1.4.197/7]
    at org.h2.mvstore.DataUtils.newIllegalStateException(DataUtils.java:870)
    at org.h2.mvstore.FileStore.open(FileStore.java:173)
    at org.h2.mvstore.MVStore.<init>(MVStore.java:350)
    at org.h2.mvstore.MVStore$Builder.open(MVStore.java:2934)
    at org.h2.mvstore.db.MVTableEngine$Store.open(MVTableEngine.java:155)
    ... 45 more

This is my H2 database console, showing the configurations that I have passed to hibernate.cfg.xml, like JDBC URL, driver class...

enter image description here I have imported H2 in POM.xml file of my project:

  <dependency>
       <groupId>com.h2database</groupId>
       <artifactId>h2</artifactId>
  </dependency>
  • 1
    Are you doing the same?resolved-error.com/questions/37006384/… – soorapadman Mar 12 at 13:10
  • No, I haven't passed an absolute path to Person.hbm.xml as he did. I don't know what is this file, and if I have to create it. My Hibernate.cfg.xml has a tag "mapping resource" pointing to it in a directory called "HibernateExposed" that must be part of Hibernate. I'm completely lost. kkk – Lucas Pletsch Mar 12 at 20:39
2

You can either define entity mapping via annotations (I prefer this) or in an XML file. Based on the error it is looking for xml file Person.hbm.xml in folder HibernateExposed (see it from your config file <mapping resource="HibernateExposed/Person.hbm.xml" />). So you need to create Person.hbm.xml file with name of entity and all attributes. E.g.

<entity-mappings>
    <entity class="your_package_name.Produto" name="Produto">        
        <attributes>
            <property name="nome"
                type="value"
                not-null="value"
                update="value"/>
//put all other attributes from Produto class
        </attributes>
   </entity>
</entity-mappings>

But in this case you do not need to use @Entity annotation. If you want to use annotations then change hibernate.cfg.xml to something like <mapping class="your_package_name.Produto"/>

  • Thank you Mara. I want to use anotations, it is simple and efficient. But I have to create a "mapping class" tag in my hibernate.cfg.xml for each entity java class that a create? – Lucas Pletsch Mar 12 at 20:26
  • Package name, is just the package where Produto.java is, on I must pass an absolute path since de root of my project directory "PDV" ? – Lucas Pletsch Mar 12 at 20:42
  • 1
    Yes you need to create <mapping class="your_package_name.Produto"/> instead of <mapping resource="HibernateExposed/Person.hbm.xml" /> and package path is path from your root – Mara Mar 12 at 21:04
  • 1
    It is database connection issue. Basically hibernate can't connect to your db because of either wrong db url, username, password or missing jars in your project. Do you have h2 jar in your project? – Mara Mar 13 at 8:24
  • 1
    According to docs it looks fine. but please double check h2database.com/html/features.html#database_url – Mara Mar 16 at 10:31
0

I solved the problems configuring hibernate using hibernate.properties file, instead of hibernate.cfg.xml.

I used H2 in memory, using the jdbc URL (one of the defaults in H2): jdbc:h2:mem:test, configured at hibernate.properties. (More in this link: http://www.h2database.com/html/features.html#database_url)

I've follow all the steps of this tutorial for the solution: https://www.youtube.com/watch?v=MA4tM17H6_M

New contributor
Lucas Pletsch is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.