Unable to create session factory in Hibernate

11,809

Solution 1

You need to create a hibernate.cfg.xml like:

 <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration>   <session-factory>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/yourDB</property>
    <property name="hibernate.connection.characterEncoding">UTF-8</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
     <property name="hibernate.current_session_context_class">thread</property>
        <property name="hibernate.connection.CharSet">utf8</property>
        <property name="hibernate.connection.characterEncoding">utf8</property>
        <property name="hibernate.connection.useUnicode">true</property>

      <!-- DB schema will be updated if needed -->
    <!-- <property name="hbm2ddl.auto">update</property> -->   </session-factory> </hibernate-configuration>

Add next code to your servlet.xml

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${database.driver}" />
    <property name="url" value="${database.url}" />
    <property name="username" value="${database.user}" />
    <property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>

And create .properties file with next code

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/yourDB
database.user=user
database.password=password
hibernate.show_sql=true

After that you could create hibernate session with next code

Session session = null;
    session = sessionFactory.openSession();
    String query = "select users.username, users.password, users.name, users.enabled, users.surname, users.email, users.gender, users.age, users.weight, users.height, users.sport, users.place, users.photo from users where users.username LIKE '%s'";
    List<Users> userInfoList = session.createSQLQuery(String.format(query, username)).addEntity(Users.class).list();
    session.close();
    session = null;

Solution 2

You are missing the hibernate config file in your class path. That can be named ad cfg.xml . Below is example for the config file. configure these elements for your DB and place this in class path.

<?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>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://${OPENSHIFT_MYSQL_DB_HOST}:3306/hibernatetrial?createDatabaseIfNotExist=true</property>
        <property name="hibernate.connection.username">username</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">false</property>
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">update </property>
        <mapping resource="hibernatemapping/mapping.xml"/>

    </session-factory>
</hibernate-configuration>
Share:
11,809
bananas
Author by

bananas

Updated on June 04, 2022

Comments

  • bananas
    bananas almost 2 years

    I am learning hibernate 4 but got stuck in creation of Session Factory and please review my code and help me to find out the cause of problem as i am using hibernate-core 5.0.6, MySQL connector 5.0.8, log4j 1.2.17,jta jar,dom4j,and jboss-logging jar and this is my code for session factory

    class HibernateUtill 
    {
    
        private static final SessionFactory sessionFactory;
            static {
                try {
                    Logger logger = Logger.getLogger("Mylogger");
                    logger.info("Trying to create a test connection with database");
                    Configuration configuration = new Configuration().configure();
                    configuration.configure();
                    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration
                            .getProperties());
                    sessionFactory = configuration.buildSessionFactory(builder.build());
                } catch (Throwable ex) {
                    System.out.println("SessionFactory creation failed with error" + ex);
                    throw new ExceptionInInitializerError(ex);
                }
    
            }
    
            public static SessionFactory getSessionFactory() {
                return sessionFactory;
    
            }
    
            public static void shutDown() {
                sessionFactory.close();
            }
    }
    

    and the error I'm getting is :

     log4j:WARN No appenders could be found for logger (org.jboss.logging).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
    SessionFactory creation failed with errororg.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
    Exception in thread "main" java.lang.ExceptionInInitializerError
        at com.commonClasses.HibernateUtil.<clinit>(HibernateUtil.java:19)
        at com.java.save.SavingObject.savingObject(SavingObject.java:13)
        at com.java.save.SavingObject.main(SavingObject.java:31)
    Caused by: org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
        at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:53)
        at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
        at org.hibernate.cfg.Configuration.configure(Configuration.java:259)
        at com.commonClasses.HibernateUtil.<clinit>(HibernateUtil.java:12)
        ... 2 more
    

    or in simple terms errororg.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource

    The things I know is the error is due to log4j and I placed log4j.properties in src folder and the code for the property file is

    # Root logger option
    log4j.rootlogger=INFO,stdout
    
    #Direct log messages to stdout
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.out
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    
    #log JDBC bind parameter runtime arguments
    log4j.logger.org.hibernate.type=trace
    

    please help me to solve this error and cause of this error too. any help is appreciated, Thanks.

  • suman tipparapu
    suman tipparapu over 8 years
    In your code you did not pass .cfg.xml file,which contains DB connection details.
  • bananas
    bananas over 8 years
    now i got it by changing the approach like sessionFactory= new Configuration().configure("configration.cfg.xml").addResourc‌​e("Employee.hbm.xml"‌​).buildSessionFactor‌​y();
  • bananas
    bananas over 8 years
    but now if I'm using same approach for two xxx.hbm.xml its not working can you help me with that and one thing i'm working with java code not servlet or jsp/spring and no annotations please
  • BValluri
    BValluri over 8 years
    Check whether your config file in the class path. Whether container able to load this file?