Hibernate not see a mapping xml file - java

im new in hibernate and try to write data in DB.
my code
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-configuration>
<session-factory name="postsess">
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/postgis</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.default_schema">public</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Mapping files -->
<mapping resource="net.sf.hibernate.examples.quickstart.Cat.hbm.xml"/>
</session-factory>
</hibernate-configuration>
HibernateUtin
package net.sf.hibernate.examples.quickstart;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import net.sf.hibernate.*;
//import net.sf.hibernate.examples.quickstart.hibernate.cfg.xml;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException("Configuration problem: " + ex.getMessage(), ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session s = (Session) session.get();
// Open a new Session, if this Thread has none yet
if (s == null) {
s = sessionFactory.openSession();
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
session.set(null);
if (s != null)
s.close();
}
}
And get an exeption
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.ExceptionInInitializerError
at net.sf.hibernate.examples.quickstart.hib_main.main(hib_main.java:14)
Caused by: java.lang.RuntimeException: Configuration problem: Resource: net.sf.hibernate.examples.quickstart.Cat.hbm.xml not found
at net.sf.hibernate.examples.quickstart.HibernateUtil.<clinit> (HibernateUtil.java:20)
... 1 more
Caused by: org.hibernate.MappingException: Resource: net.sf.hibernate.examples.quickstart.Cat.hbm.xml not found
at org.hibernate.cfg.Configuration.addResource(Configuration.java:444)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1313)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1285)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1267)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1234)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1162)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1148)
at net.sf.hibernate.examples.quickstart.HibernateUtil.<clinit>(HibernateUtil.java:18)
... 1 more
What im doing wrong. It a second try to execute simple example and again same exeption.
UPDATE
after changing path to mapping file in hibernate.cfg.xml i get another exeption in line session.save(princess);
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): net.sf.hibernate.examples.quickstart.Cat
at org.hibernate.id.Assigned.generate(Assigned.java:32)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:85)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:184)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:173)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:69)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:477)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:472)
at net.sf.hibernate.examples.quickstart.hib_main.main(hib_main.java:23)
Cat.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 15.08.2012 12:46:22 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="net.sf.hibernate.examples.quickstart.Cat" table="CAT">
<id name="id" type="java.lang.String">
<column name="cat_id" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="name" />
</property>
<property name="sex" type="char">
<column name="sex" />
</property>
<property name="weight" type="float">
<column name="weight" />
</property>
</class>
</hibernate-mapping>
and main class.
package net.sf.hibernate.examples.quickstart;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class hib_main
{
/**
* #param args
*/
public static void main(String[] args)
{
Session session = HibernateUtil.currentSession();
Transaction tx= session.beginTransaction();
Cat princess = new Cat();
princess.setName("Princess");
princess.setSex('F');
princess.setWeight(7.4f);
session.save(princess);
tx.commit();
HibernateUtil.closeSession();
}
}

Try to define your mapping resource in such way (using "/" instead of "."):
<mapping resource="net/sf/hibernate/examples/quickstart/Cat.hbm.xml"/>
I think this is a reason of your problem.
UPDATE:
About your second problem - I think that you forgot to define id generation strategy in the Cat.hbm.sql. For example:
<id name="id" column="CREDIT_CARD_ID" type="long">
<generator class="native"></generator>
</id>
UPDATE 2:
Hibernate uses it's own types. So in the declaration of id type yous should use not java.lang.String or java.lang.Integer, but simple string and integer. For example if you want to use string id you should define it as:
<id name="id" column="cat_id" type="integer">
<generator class="native"/>
</id>
Here you can find the list of hibernate's mapping types.

You have two hibernate.cfg.xml.So remove one hibernate.cfg.xml.Try to test with below structure.And resource mapping is not trouble to you.You can declare only like this
<mapping resource="Cat.hbm.xml"/>

You should use / infront of path:
<mapping resource="/net/sf/hibernate/examples/quickstart/Cat.hbm.xml"/>

I would rename Cat.hbm.xml as Cat_hbm_xml as each '.' referring to a sub package.

Related

Got Exception in thread "main" org.hibernate.HibernateException: hibernate.cgf.xml not found while running hibernate application

My Hibernate Application needs to retrieve the data stored in MySQL database.But i was successful in saving data into DB, but failed in retrieving.
Error Log
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.HibernateException: hibernate.cgf.xml not found
at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:2035)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2016)
at mypack.DataInsertion.getInfo(DataInsertion.java:39)
at mypack.DataInsertion.main(DataInsertion.java:12)
hibernate.cfg.xml (Configuration file)
<?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>
<!-- Related to the connection START -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibdb</property>
<property name="connection.user">root</property>
<property name="connection.password">admin</property>
<!-- Related to the connection END -->
<!-- Related to the hibernate properties START -->
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Related to the hibernate properties END -->
<!-- List of XML mapping files -->
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
user.hbm.xml (Mapping file)
<?xml version="1.0"?> <!-- Mapping File to POJO Class -->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="mypack.DataProvider" table="user_info">
<id name="user_id" column="id">
<generator class="assigned"/>
</id>
<property name="user_name" column = "name" />
<property name="user_address" column = "address" />
</class>
</hibernate-mapping>
DataProvider.java (POJO Class)
package mypack; //POJO Class
public class DataProvider {
private int user_id;
private String user_name;
private String user_address;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_address() {
return user_address;
}
public void setUser_address(String user_address) {
this.user_address = user_address;
}
}
DataInsertion.java (Implementation Logic)
package mypack;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class DataInsertion {
public static void main(String[] args) {
//new DataInsertion().insertInfo();
new DataInsertion().getInfo();
}
public void insertInfo()
{
Configuration con = new Configuration(); //interation with hib
con.configure("hibernate.cfg.xml"); //registering to xml
SessionFactory SF = con.buildSessionFactory(); //creating session
Session session = SF.openSession(); //opening new session
DataProvider provider = new DataProvider();
provider.setUser_id(1);
provider.setUser_name("Goutham");
provider.setUser_address("Hunsur");
Transaction TR = session.beginTransaction();
session.save(provider);
System.out.println("Object saved successfully");
TR.commit(); //saving transaction
session.close();
SF.close();
}
public void getInfo()
{
Configuration con = new Configuration();
con.configure("hibernate.cgf.xml");
SessionFactory SF = con.buildSessionFactory();
Session session = SF.openSession();
Object obj = session.load(DataProvider.class,new Integer(1)); //We are binding data into obj from DataProvider class
DataProvider dp = (DataProvider) obj; //Typecasting into DataProvider
System.out.println("Name:"+dp.getUser_name());
System.out.println("Address:"+dp.getUser_address());
session.close();
SF.close();
}
}
Please Advise me,
Thanks.
you have wrong file name with typo hibernate.cgf.xml should be hibernate.cfg.xml
You have given wrong name hibernate.cgf.xml in getInfo method. That is why you are facing issue

Unable to Load Mapper Class in Hibernate

I'm very new to Hibernate. Followed by a youtube tutorial, I created a hibernate program but getting an error. Please find the Class and the error below. Solution for this will be highly grateful.
Error:
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Oct 29, 2016 4:36:53 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Oct 29, 2016 4:36:53 AM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Exception in thread "main" org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [Emp.hbm.xml]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:229)
at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.<init>(AnnotationMetadataSourceProcessorImpl.java:104)
Main Function()
public static void main( String[ ] args ) throws ParseException {
Configuration cfg = new Configuration();
cfg.configure("Hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
String name2 = "yahoo";
LoginRegister lr = new LoginRegister();
lr.set_username(name2.toLowerCase()+"_user");
lr.set_password(name2.toLowerCase()+"_pass");
lr.set_last_update(new java.sql.Date(new SimpleDateFormat("yyyyMMdd").parse("20110210").getTime()));
s.save(lr);
s.flush();
tx.commit();
s.close();
}
POJO CLASS:
package dto;
import java.io.Serializable;
import java.sql.Date;
public class LoginRegister implements Serializable{
private int _id;
private String _username = null;
private String _password = null;
Date _last_update = null;
public LoginRegister(){}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_username() {
return _username;
}
public void set_username(String _username) {
this._username = _username;
}
public String get_password() {
return _password;
}
public void set_password(String _password) {
this._password = _password;
}
public Date get_last_update() {
return _last_update;
}
public void set_last_update(Date _last_update) {
this._last_update = _last_update;
}
public String toString(){
return
"Id : "+this._id+"\n"+
"Username : "+this._username+"\n"+
"Password : "+this._password+"\n"+
"Last Update : "+this._last_update;
}
}
Configuration File :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database Connection -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- Driver -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Language Used (Dialect) : Here SQL -->
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property><!-- URL -->
<property name="connection.username">root</property> <!-- Username -->
<property name="connection.password"></property> <!-- Password -->
<!-- To generate SQL Queries when running the program -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<!-- For JDBC Transaction -->
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- Auto Commit -->
<property name="hibernate.connection.autocommit">false</property>
<!-- Mapping Class -->
<mapping class ="Emp.hbm.xml" />
</session-factory>
</hibernate-configuration>
Entity Mapper File:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="qqqLoginRegister" table="qqqlogin_register">
<id name="_id" column="id" type="integer">
<generator class="assigned"/>
</id>
<property name="_userName" column="username" type="string"/>
<property name="_password" column="password" type="string"/>
<property name="_last_update" column="last_update" type="date"/>
</class>
</hibernate-mapping>
Locations :
Configuration FIle : srs\Hibernate.cfg.xml
Entity Mapper : src\Emp.hbm.xml
POJO : src\dto\LoginRegister.java
Main Class : src\dao\Index.java
As you are NOT using the Hibernate bean annoatations, in your Hibernate.cfg.xml file, you need to change <mapping class ="Emp.hbm.xml" /> to <mapping resource ="Emp.hbm.xml" />
Hibernate is an ORM framework which maps the Java Bean to a Relational database table and the mapping can be provided directly in the Java Bean Object (using Annotations) or can be provided separately through xml files (like how you did).
Hibernate SessionFactory mappings are compiled from various XML mapping files and <mapping resource is used to load those mapping files (in your case it is a single file which is Emp.hbm.xml file)
You can refer the below documentation for more details:
https://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html

Hibernate, delete from collection

I have a database that contain 2 tables that connect by one-to-many relationship. I enteract with that database through Hibernate.
This is hbm.xml files:
question.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="app">
<class name="Question" table="Question">
<id name="id" column="id" type="java.lang.Long">
<generator class="native"/>
</id>
<property name="text" column="text" type="java.lang.String" not-null="true"/>
<set name="answers" cascade="all">
<key column="question_id"/>
<one-to-many class="Answer"/>
</set>
</class>
</hibernate-mapping>
answer.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="app">
<class name="Answer" table="Answer">
<id name="id" column="id" type="java.lang.Long">
<generator class="native"/>
</id>
<property name="text" column="text" type="java.lang.String" not-null="true"/>
<many-to-one name="question" column="question_id" class="Question" not-null="true"/>
</class>
</hibernate-mapping>
And this is java files:
Question.java
package app;
import java.util.Set;
public class Question {
Long id = null;
String text = "";
Set<Answer> answers = null;
// getters and setters
}
Answer.java
package app;
public class Answer {
Long id = null;
String text = "";
boolean isTrue = false;
Question question = null;
// getters and setters
}
So Question can have Answers and Question instance has a collection fo Answers instances.
This is main method:
package application;
import app.Answer;
import app.Question;
import java.util.HashSet;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Application {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Question question = new Question();
question.setText("question1");
Answer answer1 = new Answer();
answer1.setText("answer1");
answer1.setQuestion(question);
Answer answer2 = new Answer();
answer2.setText("answer2");
answer2.setQuestion(question);
HashSet<Answer> answers = new HashSet<>();
answers.add(answer1);
answers.add(answer2);
question.setAnswers(answers);
session.beginTransaction();
try {
session.saveOrUpdate(question);
session.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
session.getTransaction().rollback();
}
answers.remove(answer2);
session.beginTransaction();
try {
session.saveOrUpdate(question);
session.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
session.getTransaction().rollback();
}
}
}
So I create Question instance, add two Answers instances to collection in Question instance and save Question instance in database. All work correctly - Question and Answers is writen to database.
Then I remome one of Answers instance from collection in Question instance and try to save Question instance in database again. I catch an Exception. It's in my native language, but it is SQLServerException and it say something like this: "Can't insert NULL in column "question_id" in table "Test.dbo.Answer", in this column NULL is forbidden. Error in UPDATE"
What's wrong? How can I delete one of Answer from Question?
In a bidirectional relationship one side has to be the inverse one. In a one-to-many association that is usually the one- side:
<set name="answers" cascade="all" inverse="true">
<key column="question_id"/>
<one-to-many class="Answer"/>
</set>
This way only many- side will take care of the relationship.
In your case, both sides do it, and since the foreign key is in the Answer class/table, Hibernate updates it to null when flushing the association changes in the Question class.
saveOrUpdate() is only for createing a new record if doesnt exist or updating if it does exist.Please find the pseudocode below.
Question question = new Question();
question.setText("question1");
Answer deleteAns=new Answer();
deleteAns.setText("answer2");
question.setAnswer(deleteAns);
session.dele‌​te(question)

HIbernate Stateless Session entity configuration

We are using hibernate to populate a ddbb with data from multiples files. Multiples threads are proccessing the files and when x files are processed we flush the data on the database.
When i try to write on the database we get the next error:
core.exception.SavingException: org.hibernate.MappingException: Unknown entity: FilesPT
at databaseaccess.session.GenericManagerImpl.insertBatch(GenericManagerImpl.java:75)
at FileWriter.flushFiles(FileWriter.java:425)
Caused by: org.hibernate.MappingException: Unknown entity: FilesPT
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:597)
at org.hibernate.impl.StatelessSessionImpl.getEntityPersister(StatelessSessionImpl.java:376)
at org.hibernate.impl.StatelessSessionImpl.insert(StatelessSessionImpl.java:80)
at databaseaccess.dao.GenericDAOImpl.insertList(GenericDAOImpl.java:36)
at session.GenericManagerImpl.insertBatch(GenericManagerImpl.java:72)
... 4 more
My Hibernate config file is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"classpath://org/hibernate/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#%DB_HOST%:%DB_PORT%:%DB_SID%</property>
<property name="hibernate.connection.username">%DB_USER%</property>
<property name="hibernate.connection.password">%DB_PASS%</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.default_schema">%DB_SCHEMA%</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.format_sql">false</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<mapping resource="databaseaccess/entities/Files.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The file databaseaccess/entities/Files.hbm.xml has two different entities:
<hibernate-mapping>
<class name="databaseaccess.entities.Files" table="FILES_PT" entity-name="FilesPT">
<id name="dealId" column="FILE_ID" type="java.lang.String" length="50" />
<property name="filename" column="FILENAME" type="java.lang.String" length="250" />
<property name="folder" column="FOLDER" type="java.lang.String" length="30" />
</class>
<class name="databaseaccess.entities.Files" table="FILES_ES" entity-name="FilesES">
<id name="dealId" column="FILE_ID" type="java.lang.String" length="50" />
<property name="filename" column="FILENAME" type="java.lang.String" length="250" />
<property name="folder" column="FOLDER" type="java.lang.String" length="30" />
</class>
</hibernate-mapping>
To save the data we are using an Stateless session generated from the hibernateUtil:
public void insertList(final String entityName, final Collection entities) {
StatelessSession session = HibernateUtil.openStatelessSession();
try {
Transaction tx = session.beginTransaction();
try {
for (Object entity : entities) {
session.insert(entityName, entity);
}
tx.commit();
} catch (final HibernateException e) {
logger.error("Error inserting " + entities.size() + " rows in database. " + e.getMessage() + ":\n "
+ e.getMessage());
throw e;
} finally {
tx.rollback();
}
} finally {
session.close();
}
}
The hibernate util generate a static session factory
static {
try {
// Create the SessionFactory from config file.
File fileCfgHibernate = new File(ConfigurationManager.getProperty("Global.properties", "HIBERNATE_CFG_FILE"));
logger.info("Opening DB session with configuration from: " + fileCfgHibernate.getPath());
Configuration cfgHibernate = new Configuration().configure(fileCfgHibernate);
sessionFactory = cfgHibernate.buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
logger.error("DB session creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static StatelessSession openStatelessSession() {
return sessionFactory.openStatelessSession();
}
We have checked that the session factory use the configuration on the hibernate.cfg file but it seems that the session is not getting the configuration. What are we missing?

How to solve this hibernate runtime exception?

I am trying to run following code in eclipse
package com.trial;
import java.sql.*;
import java.io.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class AddStudent {
private static SessionFactory sessionFactory;
public static void main(String args[]) throws Exception {
DataInputStream d = new DataInputStream(System.in);
System.out.println("ENTER YOUR NAME");
String name = d.readLine();
System.out.println("ENTER YOUR DEGREE");
String degree = d.readLine();
System.out.println("ENTER YOUR PHONE");
int phone = Integer.parseInt(d.readLine());
System.out.println("Name: " + name);
System.out.println("Degree: " + degree);
System.out.println("Phone: " + phone);
if ((name.equals("") || degree.equals(""))) {
System.out.println("Information Required");
}
else {
try {
sessionFactory = new Configuration().configure("com//xml//hibernate.cfg.xml").buildSessionFactory();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
Session s = sessionFactory.openSession();
Student stu = new Student();
stu.setName(name);
stu.setDegree(degree);
stu.setPhone(phone);
s.save(stu);
System.out.println("Added to Database");
if (s != null)
s.close();
}
}
}
But getting Runtime exception during creating session factory object that Unable to read XML.
I am using following xml files
hibernate.cfg.xml
<!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 name="studentFactory">
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/ganeshdb</property>
<property name="connection.username">****</property>
<property name="connection.password">****</property>
<property name="connection.pool_size">10</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="com//xml//student.hbm.xml" />
</session-factory>
</hibernate-configuration>
Mapping File
<?xml version="1.0"? encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/hibernate-configuration-3.0.dtd">
<hibernate-mapping>
<class name="com.trial.Student" table="studentdemo">
<id name="id" type="int" column="ID">
<generator class="increment" />
</id>
<property name="name" column="name" />
<property name="degree" column="degree" />
<property name="phone" column="phone" />
</class>
</hibernate-mapping>
plz help.
<mapping resource="student.hbm.xml" />
and make sure it is in same direcotry as hibernate.cfg.xml

Categories