11

I'm trying to use hibernate with spring 3 mvc but at the moment I get this exception thrown. I think I need to define my hibernate.cfg.xml somewhere, but not sure where?

I basically followed this example here http://www.nabeelalimemon.com/blog/2010/05/spring-3-integrated-with-hibernate-part-a/ And in particularly saw this line of code there that suppose to "magically" find my hibernate.cfg file using this:

return new Configuration().configure().buildSessionFactory();

I'm guessing that is not correct? i currently have my hibernate.cfg file inside src/com/jr/hibernate/

below is my cfg file:

<?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/racingleague</property>
    <property name="connection.username">username</property>
    <property name="connection.password">password</property>
    <property name="hibernate.format_sql">true</property>
    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>
    <!-- SQL dialect -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</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="hibernate.show_sql">true</property>
    <!-- Drop and re-create the database schema on startup -->
    <property name="hibernate.hbm2ddl.auto">update</property>
    <!--property name="hbm2ddl.auto">update</property-->
    <mapping resource="com/jr/model/hibernateMappings/user.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

my hibernate utils class:

package com.jr.utils;

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

public class HibernateUtils {

     private static final SessionFactory sessionFactory = buildSessionFactory();

      public static SessionFactory buildSessionFactory() {
        try {
          // Create the SessionFactory from hibernate.cfg.xml
          return new Configuration().configure().buildSessionFactory();
        }
        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);
        }
      }

}

which gets called bu this abstract class:

package com.jr.db;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import com.jr.utils.HibernateUtils;

public abstract class DbWrapper<T> {

    private static SessionFactory sessionFactory = null;
    private static Session session;

    public DbWrapper() {
        setSessionFactory();
    }

    private void setSessionFactory() {
        sessionFactory = HibernateUtils.buildSessionFactory();
        session = sessionFactory.getCurrentSession();
    }

    public boolean addNewItem(T dbItem) {

        try {
            session.getTransaction().begin();
            session.save(dbItem);
            session.getTransaction().commit();
        } catch (Exception e) {
            System.err.println("error exception when adding new item to table"
                    + e);
        } finally {

            session.close();
            sessionFactory.close();
        }

        return false;

    }

    public abstract boolean removeItem(String uid);

    public abstract boolean modifyItem(String uid, T item);

}

And here is the controller that originally does some hibernate stuff:

private Logger logger = Logger.getLogger(UserController.class);

    private UserDb userDb;

@RequestMapping(value = "/user/registerSuccess", method = RequestMethod.POST)
public String submitRegisterForm(@Valid User user, BindingResult result) {

    // validate the data recieved from user
    logger.info("validate the data recieved from user");
    if (result.hasErrors()) {
        logger.info("form has "+result.getErrorCount()+" errors");

        return "account/createForm";
    } else{
        // if everthings ok, add user details to database
        logger.info("if everthings ok, add user details to database");

        userDb = new UserDb();

        userDb.addNewItem(user);

        // display success and auto log the user to the system.
        return "account/main";
    }

}

Cheers in advance. I also have all my table hibvernate xml mappings in the same location as my hibernate.cfg.xml file

7 Answers 7

28

Instead of placing hibernate.cfg.xml file under src/com/jr/hibernate/ directory, place it under src directory. It will then automatically appear in WEB-INF/classes directory, as mentioned by the folks here.

Sign up to request clarification or add additional context in comments.

2 Comments

cheers. it works. i have another question. my app cannot seem to locate my hibernate xml mappings. i have it places in com.jr.hibernateMappings but the build.xml doesnt seem to build and compile my hbm.xml files. is it in the wrong location again? does it need to be in the WAR/WEB-INF/classes folder? i would much prefer it be inside the src directory if possible
Thanks...after moving my file(hibernate.cfg.xml) to src it will locate the file thanks very much again
14

hibernate.cfg.xml must be found in the root of the classpath when the webapp is started.

If you are using maven to build the project, put hibernate.cfg.xml in the src/main/resources directory so that when you build the war package, it will be automatically be placed in /WEB-INF/classes.

If not using maven, place the file directly in your WEB-INF/classes directory.

Comments

3

hibernate.cfg.xml should be in WEB-INF/classes. Alternatively, you can load it from a custom location by passing the corresponding argument to the configure(..) method.

1 Comment

Bozho, config.configure("/resources/hibernate.cfg.xml"); does not work for me. Actually, I am doing a simple hibernate 3.1 app. Btw, config is of type AnnotationConfiguration.
3

If you using Maven you should put file hibernate.cfg.xml in following path /src/main/java/resources/hibernate.cfg.xml in Intellij IDEA. Then, in your run application class just insert line:

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

2 Comments

Thnx. I almost wasted 2 days after this.
then what about NetBeans?
1

In IntelliJ go to "Open Project Settings" >> Modules >> Hibernate and target your hibernate.cfg.xml file used in your project.

1 Comment

I had already done the above solutions where the hibernate.cfg.xml was the under the src directory but the problem persisted. until I followed the step of @Epredator of opening the Project settings -> Modules ->HIbernate
0

I have the same problem and moved hibernate.cfg.xml to the src/main/resources directory solved, it will be automatically be placed in /WEB-INF/classes.

Comments

0

Even if i had hibernate.cfg.xml under src folder, i get

 org.hibernate.HibernateException: /hibernate.cfg.xml not found

after running mvn clean install. With Try and error i was able to resolve it by removing hibernate.cfg.xml from src folded and add to to somewhere else. Run the app(It is a main class in my case). During this I still get the error. and add it back to src folder and rum the main class. It worked!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.