asteriskNinja asteriskNinja - 5 months ago 60
Java Question

Unable to create session factory in Hibernate

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.

Answer

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