I am new to Hibernate.
When I run my Hibernate program using Eclipse, it is able to find hibernate.cfg.xml file.
I put that file into src/main/resources folder.
But when I create executable jar and run my program using
java -jar SQ.jar
It is giving me following error
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.moodys.sonarqube.ExtractSQData.HibernateUtil.buildSessionFactory(HibernateUtil.java:20)
at com.moodys.sonarqube.ExtractSQData.HibernateUtil.<clinit>(HibernateUtil.java:9)
at com.moodys.sonarqube.ExtractSQData.SQ.getProjectDB(SQ.java:266)
at com.moodys.sonarqube.ExtractSQData.SQ.extractSQDataToDB(SQ.java:76)
at com.moodys.sonarqube.ExtractSQData.SQ.main(SQ.java:59)
Caused by: org.hibernate.HibernateException: /hibernate.cfg.xml not found
at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1405)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1427)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1414)
at com.moodys.sonarqube.ExtractSQData.HibernateUtil.buildSessionFactory(HibernateUtil.java:14)
... 4 more
Following is the code where I load my hibernate.cfg.xml file
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().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);
}
}
Please advise me what I am doing wrong.
You can give the full path while configure it.
You can try this.
return new AnnotationConfiguration().configure("/resources/hibernate.cfg.xml").buildSessionFactory();
or
return new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();
You can try this one also if you are using hibernate 4.3+
configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder serviceBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(serviceBuilder.build());
Related
I have new spring-boot project. I use gradle as build manager and Eclpice IDE. I want to use hibernate and try to get configurations from hibernate.cfg.xml file, but get
org.hibernate.HibernateException: /hibernate.cfg.xml not found
I store this file in resources folder, also I tried put it into META-INF folder.
folders structure:
HibernateUtil.java:
public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try
{
if (sessionFactory == null)
{
sessionFactory = new Configuration().configure().buildSessionFactory();
}
return sessionFactory;
} catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
If you want to read the files in the resources directory, you need to use the classloder to get the file.
In static method
HibernateUtil.class.getClassLoader().getResource("hibernate.cfg.xml").getFile();
non static method
getClass().getClassLoader().getResource("hibernate.cfg.xml").getFile();
and if the resource resides in any of the sub directories of resources, prefix the folder path while getting the resource
Example to get the resource in META-INF directory
getResource("META-INF/hibernate.cfg.xml");
But spring boot auto configures, just by adding dependencies in pom.xml and providing JPA related properties in application.properties
if your application is web Service,you should put hibernate.cfg.xml in WEB-INF floder.if your application is client service, you should put your hibernate.cfg.xml in src package.
I was trying to connect a simple java application with mysql db using hibernate. I have already created the schema in my db and this java application is simply creating a table in this schema and inserting data in it.All the time I am getting same error.
My Code is as follows:
hibernate.cfg.xml
UserDetails.java
HibernateTest.java
Error:
Please help me, I have been stuck for quite a long time.
Thanks !!
Seems like a duplicate of Exception in thread "main" java.util.ServiceConfigurationError
Seems that your using hibernate >=4 and the setup procedure from hibernate <4.
Correct way according to the link is.
Configuration configuration = new Configuration().configure();
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
//check External Jar files whether you added properly or not...if not remove all jar files and add once again...
After Main
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session session = sf.OpenSession();
UserDetails ud = new UserDetails();
ud.setName("bdskbf");
ud.setId(23);
Transaction tnx = session.beginTransaction();
session.save(ud);
tnx.getTransaction.commit();
I created a project with following structure:
HibernateUtil:
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\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);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
at line
Configuration configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
I have error
Initial SessionFactory creation
failed.org.hibernate.HibernateException:
C:\Users\Nikolay_Tkachev\workspace\hiberTest\src\logic\hibernate.cfg.xml
not found Exception in thread "main"
java.lang.ExceptionInInitializerError at
logic.HibernateUtil.buildSessionFactory(HibernateUtil.java:19) at
logic.HibernateUtil.(HibernateUtil.java:9) at
logic.Main.main(Main.java:12) Caused by:
org.hibernate.HibernateException:
C:\Users\Nikolay_Tkachev\workspace\hiberTest\src\logic\hibernate.cfg.xml
not found at
org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173)
at
org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1947)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1928)
at logic.HibernateUtil.buildSessionFactory(HibernateUtil.java:14)
... 2 more
What is the reason for the error and how do I fix it?
Give the path relative to your project.
Create a folder called resources in your src and put your config file there.
configuration.configure("/resources/hibernate.cfg.xml");
And If you check your code
Configuration configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
return new Configuration().configure().buildSessionFactory();
In two lines you are creating two configuration objects.
That should work(haven't tested) if you write,
Configuration configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
return configuration.buildSessionFactory();
But It fails after you deploy on the server,Since you are using system path than project relative path.
Somehow placing under "src" folder didn't work for me.
Instead placing cfg.xml as below:
[Project Folder]\src\main\resources\hibernate.cfg.xml
worked.
Using this code
new Configuration().configure().buildSessionFactory().openSession();
in a file under
[Project Folder]/src/main/java/com/abc/xyz/filename.java
In addition have this piece of code in hibernate.cfg.xml
<mapping resource="hibernate/Address.hbm.xml" />
<mapping resource="hibernate/Person.hbm.xml" />
Placed the above hbm.xml files under:
EDIT:
[Project Folder]/src/main/resources/hibernate/Address.hbm.xml
[Project Folder]/src/main/resources/hibernate/Person.hbm.xml
Above structure worked.
You can put the file "hibernate.cfg.xml" to the src folder (src\hibernate.cfg.xml) and then init the config as the code below:
Configuration configuration = new Configuration();
sessionFactory =configuration.configure().buildSessionFactory();
This is an reality example when customize folder structure:
Folder structure, and initialize class HibernateUtil
with:
return new Configuration().configure("/config/hibernate.cfg.xml").buildSessionFactory();
mapping:
with customize entities mapping files:
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="com.vy.entities.Users"/>
<mapping class="com.vy.entities.Post"/>
<mapping resource="config/Users.hbm.xml"/>
<mapping resource="config/Post.hbm.xml"/>
</session-factory>
</hibernate-configuration>
(Note: Simplest way, if you follow default way, it means put all xml config files inside src folder, when build sessionFactory, only:
return new Configuration().configure().buildSessionFactory();
)
For anyone interested: if you are using Intellj, just simply put hibernate.cfg.xml under src/main/resources.
try below code it will solve your problem.
Configuration configuration = new Configuration().configure("/logic/hibernate.cfg.xml");
My problem was that i had a exculding patern in the resorces folder.
After removing it the
config.configure();
worked for me. With the structure
src/java/...HibernateUtil.java and cfg file under src/resources.
Another reason why this exception occurs is if you call the configure method twice on a Configuration or AnnotatedConfiguration object like this -
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(MyClass.class);
//Use this if config files are in src folder
config.configure();
//Use this if config files are in a subfolder of src, such as "resources"
config.configure("/resources/hibernate.cfg.xml");
Btw, this project structure is inside eclipse.
Using configure() method two times is responsible the problem for me. Instead of using like this :
Configuration configuration = new Configuration().configure();
configuration.configure("/main/resources/hibernate.cfg.xml");
Now, I am using like this, problem does not exist anymore.
Configuration configuration = new Configuration();
configuration.configure("/main/resources/hibernate.cfg.xml");
P.S: My hibernate.cfg.xml file is located at "src/main/resources/hibernate.cfg.xml",too.
The code belove works for me. at hibernate-5
public class HibernateUtil {
private static SessionFactory sessionFactory ;
static {
try{
Configuration configuration = new Configuration();
configuration.configure("/main/resources/hibernate.cfg.xml");
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
catch(Exception e){
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
In case of a Maven Project, create a folder named resources under src/main folder and add the resources folder as a source folder in your classpath.
You can do that by going to Configure Build Path and then clicking Add Folder to the Sources Tab.
Then check the resources folder and click Apply.
Then just use :
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
I downloaded Hibernate 4.1.2 and am using Oracle Database 10g Release 2. The JDBC driver I am using is ojdbc14.jar.
I set up HibernateUtil class as:
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
// Create the SessionFactory from hibernate.cfg.xml
try{
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
return configuration.buildSessionFactory(serviceRegistry);
}catch(HibernateException ex){
ex.printStackTrace();
throw ex;
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
In hibernate.properties I have:
hibernate.dialect org.hibernate.dialect.OracleDialect
hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver
hibernate.connection.username HR
hibernate.connection.password HR
hibernate.connection.url jdbc:oracle:thin:#localhost:1521/xe
But Hibernate doesn't want to load the driver. It throws an exception saying 'No appropriate driver found'.
I tried to load the driver with Class.forName("oracle.jdbc.driver.OracleDriver"); and it works fine.
The problem was in using the wrong JDBC Oracle driver. When I tried with ojdbc6.jar everything worked fine.
A couple of things:
Try to make the properties file valid by putting = between key and value
Check that there aren't any trailing spaces after the values
Use oracle.jdbc.OracleDriver instead of oracle.jdbc.driver.OracleDriver. See Difference between Oracle jdbc driver classes? for further reference.
Your connection URL is configured wrongly, should be:
hibernate.connection.url jdbc:oracle:thin:#localhost:1521:xe
More information for Oracle's URL can refer here.
As other answer point out:
Use oracle.jdbc.OracleDriver instead of oracle.jdbc.driver.OracleDriver
I need to provide a jar file which provides an API to retrieve the records from the database using Hibernate.
For example I have an API:
public List getUsers(String locationOfHibernateConfigFile) {
}
I tried by passing the location of the config file with the complete path using c:\hibernate-cfg.xml as shown below:
SessionFactory sessionFactory = new Configuration()
.configure(C:\hibernate.cfg.xml).buildSessionFactory();
session = sessionFactory.openSession();
I am getting an error saying c:\hibernate-cfg.xml is not found.
Please provide me some pointers to achieve the same.
SessionFactory sessionFactory = new Configuration()
.configure("hibernate.primaryKeys.cfg.xml")
.buildSessionFactory();
Where hibernate.primaryKeys.cfg.xml is a user-defined hibernate file.
This will work, but ensure hibernate.primaryKeys.cfg.xml is in your classpath.
Well try it:
File file = new File("C:\hibernate.cfg.xml");
SessionFactory sessionFactory = new Configuration().configure(file).buildSessionFactory();
But it is not advisable to leave this type of configuration on C:.
You can read file and properties:
Just put your file hibernate.cfg.xml into the resources folder.
Properties properties = new Configuration().configure().getProperties();
String driver = properties.getProperty("hibernate.connection.driver_class");
String url = properties.getProperty("hibernate.connection.url");
String username = properties.getProperty("hibernate.connection.username");
String password = properties.getProperty("hibernate.connection.password");