11

I am trying to connect to Postgresql9.1 in ubuntu with pgadmin3. My Pgadmin3 GUI tool does not give any option to create tables by right clicking the database, but it is available in some videos I saw. Therefore, I used terminal to create the database and it showed up in pgadmin3.

my file structure

My Userdetails file

package org.nitish.hiber;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class UserDetails {
    @Id
    private int userId;
    private String userName;
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
}

My HibernateCaller file

package org.nitish.caller;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.nitish.hiber.UserDetails;

public class HibernateTest {

    public static void main(String[] args) {
        UserDetails user = new UserDetails();
        user.setUserId(1);
        user.setUserName("First User");
        try {
            SessionFactory sessionFactory = new Configuration().configure("/HibernateTest/src/hibernate.cfg.xml").buildSessionFactory();
            Session session = sessionFactory.openSession();
            session.beginTransaction();
            session.save(user);
            session.getTransaction().commit();

        } catch(HibernateException e) {
            e.printStackTrace();
        }
    }

}

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, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<hibernate-configuration>

  <session-factory>
    <!-- Database connection settings -->
    <property name="connection.driver_class">org.postgresql.Driver  </property>
    <property name="connection.url">jdbc:postgresql://localhost:5432/hiber</property>
    <property name="connection.username">nitish</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.PostgreSQLDialect</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.internal.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 class="org.nitish.hiber.UserDetails"/>
  </session-factory>
</hibernate-configuration>

I am getting following error

Mar 1, 2016 9:02:48 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 1, 2016 9:02:48 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [/HibernateTest/src/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 org.nitish.caller.HibernateTest.main(HibernateTest.java:17)

After making few changes (could not use session.close() in finally block I think that should not cause this error)

Mar 1, 2016 10:13:34 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
Mar 1, 2016 10:13:34 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 1, 2016 10:13:34 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Mar 1, 2016 10:13:34 AM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead.  Support for obsolete DTD/XSD namespaces may be removed at any time.
Mar 1, 2016 10:13:35 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Mar 1, 2016 10:13:35 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
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:244)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
    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:217)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
    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:418)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:692)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
    at org.nitish.caller.HibernateTest.main(HibernateTest.java:17)
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.postgresql.Driver]
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:229)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.loadDriverIfPossible(DriverManagerConnectionProviderImpl.java:161)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildCreator(DriverManagerConnectionProviderImpl.java:117)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:73)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
    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:234)
    ... 14 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.postgresql.Driver
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:217)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:323)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:268)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:274)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:226)
    ... 25 more
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
nitishpisal
  • 143
  • 1
  • 2
  • 9

12 Answers12

14

If you have your hibernate.cfg.xml in the root of the source folder, just do

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

If it is in the package, for an example in the org.nitish.caller, specify path by this way

 SessionFactory sessionFactory = new Configuration()
    .configure("/org/nitish/caller/hibernate.cfg.xml").buildSessionFactory();

You need to close the session (in the finally block). Don't forget to add rollback code.

Please, add @Table annotation to the UserDetails.

Update

The reason of the error that Hibernate can't find org.postgresql.Driver class. It resides in postgresql jar. You have that jar at your image, but may be you don't add it to the classpath. Refer How to Add JARs to Project Build Paths in Eclipse (Java).

To close a session in the finally block you need to have session variable outside the try block.

    Session session = sessionFactory.openSession();

    try{

    } finally {
        session.close();
   }
v.ladynev
  • 19,275
  • 8
  • 46
  • 67
6

I fixed this by moving my config file to src/main/resources. This is the standard directory for configuration files like hibernate.cfg.xml or hibernate.properties or application related properties files.

Gana
  • 482
  • 3
  • 11
  • 32
ASH
  • 980
  • 1
  • 9
  • 22
5
new Configuration().configure(new File("hibernate.cfg.xml")).buildSessionFactory());

This solved the error for me!

Mohamed Anees A
  • 4,119
  • 1
  • 22
  • 35
2

new Configuration().configure() takes hibernate.cfg.xml from root of class path directory. new Configuration().configure("/com/company/project/hibernate.cfg.xml") takes from root of class path + com/company/project/hibernate.cfg.xml.

If you are using different file name for hibernate configuration from root of class path, then eg: new Configuration().configure("/database.cfg.xml")

If you want to give the full system path of the configuration file then new Configuration().configure(new File("/home/visruth/config/hibernate.cfg.xml)) which takes the configuration file from the given exact location.

Visruth
  • 3,430
  • 35
  • 48
1

All the previous answers are perfect. However, if u need a really quick solution then I would recommend you to just put your hibernate.cfg.xml file in your source folder and write

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

This is simple and works!

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
0

You have to use the absolute path of the file otherwise this will not work. Then with that path we build the file and pass it to the configuration.

private fun getFile(): File {
    val currentWorkingDir = System.getProperty("user.dir")
    val absoulutePath = "$currentWorkingDir/src/main/resources/secret-hibernate.cfg.xml"
    println("Absolute Path of secret-hibernate.cfg.xml: $absoulutePath")
    return File(absoulutePath)
}

https://stackoverflow.com/a/64084771/5279996

GL

Braian Coronel
  • 22,105
  • 4
  • 57
  • 62
0

Create a folder in src/main named "resources" Place the hiberenate.cfg.xml file in it Create the session factory object as SessionFactory factory = new Configuration().configure().buildSessionFactory();

This will successfully create the object You can verify it by checking this should print false System.out.println(factory.isClosed());

This worked for me!

Shreyas K
  • 1
  • 2
0

Answer is right there in the first line of error (question) , if you read carefully , it says : Could not locate cfg.xml resource >> resource

Seems there was nothing found in resource or may be resource is not set-up correctly

If you are using IDE such as Intellij :

  • Make sure you save your hibernate.cfg.xml under src/main/resources/<Your_config_xml_here>

example : src/main/resources/hibernate.cfg.xml

  • This is important ( I have personally faced this almost always during initial set up of java/maven..)

So, make sure you mark resources directory as Resources root so that it looks
example , look at this image

How to mark a folder as Resources root
Before After (look at 3 lines)

Now compile and build : A new jar will be build linking all files with latest changes , and you will no more be complained of missing hibernate.cfg.xml

eaccmk
  • 366
  • 2
  • 6
0

Create a file in the src or root directory project, named: "hibernate.cfg.xml".

 <?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="connection.driver_class">com.mysql.jdbc.Driver</property>
     <property name="connection.url">jdbc:mysql://localhost/hibernate1</property>     <property name="connection.username">hibernate1</property>
     <property name="connection.password">hibernate1</property>
     <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
     <property name="hibernate.show_sql">true</property>

   </session-factory>
 </hibernate-configuration>

In your class

  package io.yourPack;


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


public class hibernateClass  {
    
     public static void main(String[] args) {
         
         SessionFactory myFactory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(clima.class).buildSessionFactory();
            
            Session mySession = myFactory.openSession();
            
            try {
                
                yourClass cl1 = new yourClass("java", "1,2,3", 6);
                
                mySession.beginTransaction();
                
                mySession.save(cl1);
                
                mySession.getTransaction().commit();
                
                System.out.println("Inserted !!");
                
                mySession.close();
                
            }finally {
                myFactory.close();
            }
         
     }
    

}
Hamada
  • 1,836
  • 3
  • 13
  • 27
0

If you are using maven build tool for hibernating configuration then you should use resource folder inside src/main folder. it will surely solve your problem. I was facing the same issue

0

update modify and write hibernate-cfg.xml file

  • This answer doesn't seem to be a full answer and appears to be just rephrasing what other answers have already said. Please add more details to the answer to make it helpful and distinct. – DeadChex Apr 07 '23 at 20:51
0

Bro , I was facing same error and I realized that I was not having any folder called resources in my src/main so I just created one and make my hibernate.cfg.xml file there and it WORKS.

This is first time I'm giving solution to someone on stackoverflow I hope it helps :)

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 02 '23 at 23:17