Hibernate is an Object/ Relational Mapping solution for Java environments. It reduces the development cost by reducing paradigm mismatch between how data is represented in objects versus relational databases.
Hibernate takes care of the mapping from Java classes to database tables and provides data query and retrieval facilities. This tutorial is designed for the beginners of Hibernate and expects you to have some knowledge about Java and SQL. I’m going to use MySQL database and Eclipse IDE in this tutorial.
By following this tutorial you will get the knowledge of;
1. Setup the Development Environment for Hibernate
Let's start.
1. Setup the Development Environment for Hibernate
First you need to set up the development environment. Following things are needed if you want to try Hibernate with MySQL using Eclipse IDE.
1. Hibernate distribution bundle – Download
2. MySQL installed in your Computer – Download
3. JDBC driver for MySQL – Download
4. slf4j logging backend – Download
5. Eclipse IDE – Download
1.1 Setup the Database
I'm going to use simple database named "userdata" which has two tables named "users" and "tasks". Figure 1 illustrates the structure of the database and there "id" column is the Primary Key of both tables and it is set to AUTO_INCREMENT.
1.2 Create New Project
In this tutorial I’m going to show how to Retrieve, Add, Delete and Update data in a MySQL database. There I’ll create simple Java Project and you can use this tutorial to create web applications too.
First create new project in Eclipse using appropriate name, I’ll give "MyFirstHibernateApp".
You need to manually account for all the needed dependencies, so let’s create new folder called "lib" inside the "MyFirstHibernateApp" by right clicking on it as shown in following Figure 3.
Now copy following files into that folder.
Then you can configure the built path. To do that, right click on project "MyFirstHibernateApp" in Package Explorer and select Build Path --> Configure Build Path... Then go to Libraries tab and browse lib folder you created earlier. Then add external jars by selecting all jar files that you copied to lib folder in one of previous step. (Check Figure 4).
Now you will be able to see the referenced libraries as follow (Figure 5).
2. Create POJO Classes
Next, I'll create two classes that represent the user and task we want to store in the database. Those are simple JavaBean classes with some properties which uses standard JavaBean naming conventions for property getter and setter methods and private visibility for the fields.
To create new class right click on "MyFirstHibernateApp" and select New --> Class. Then give appropriate package name, I’ll give "com.hib" as figure 6. You can generate getter and setters easily by selecting variable declaration and selecting Source --> Generate Getters and Setters…
User Class
3. Create Mapping Files
Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.
Right click on the "src" folder and select New --> File and paste following code there. Save it as user.hbm.xml.
The id element is the declaration of the identifier property. The name="id" mapping attribute declares the name of the JavaBean property and tells Hibernate to use the getId() and setId() methods to access the property. The column attribute tells Hibernate which column of the "users" and "tasks" tables holds the primary key value. Similar to the id element, the name attribute of the property element tells Hibernate which getter and setter methods to use.
4. Hibernate Configuration
Now you have the persistent class and its mapping file in place. Let’s configure Hibernate.
Right click on the "src" folder and select New --> File and paste following code there. Save it as hibernate.cfg.xml. Here you have to give the username and password according to your MySQL account. In my case username is root and there is no password.
You have to startup Hibernate by creating a global org.hibernate.SessionFactory object and storing it somewhere for easy access in your application code. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once. We will create a HibernateUtil helper class that takes care of startup and makes accessing the org.hibernate.SessionFactory more convenient.
To create new class right click on "com.hib" package and select New --> Class and give Name as HibernateUtil.java and paste the following code in class file.
Now it’s time to do some real work using Hibernate. Following test class illustrate how we can Add, Retrieve, Update and Delete data in a MySQL database.
To create new class right click on "com.hib" package and select New --> Class and give Name as Test.java and paste the following code in class file.
I have included the source files of this tutorial with the database. You can download it from here (Password : sara).
Hibernate takes care of the mapping from Java classes to database tables and provides data query and retrieval facilities. This tutorial is designed for the beginners of Hibernate and expects you to have some knowledge about Java and SQL. I’m going to use MySQL database and Eclipse IDE in this tutorial.
By following this tutorial you will get the knowledge of;
1. Setup the Development Environment for Hibernate
2. Create POJO Classes
3. Create Mapping Files
4. Hibernate Configuration
5. Create Startup Helper Class
6. Create Test Class to Load and Store Objects
Let's start.
1. Setup the Development Environment for Hibernate
First you need to set up the development environment. Following things are needed if you want to try Hibernate with MySQL using Eclipse IDE.
1. Hibernate distribution bundle – Download
2. MySQL installed in your Computer – Download
3. JDBC driver for MySQL – Download
4. slf4j logging backend – Download
5. Eclipse IDE – Download
1.1 Setup the Database
I'm going to use simple database named "userdata" which has two tables named "users" and "tasks". Figure 1 illustrates the structure of the database and there "id" column is the Primary Key of both tables and it is set to AUTO_INCREMENT.
1.2 Create New Project
In this tutorial I’m going to show how to Retrieve, Add, Delete and Update data in a MySQL database. There I’ll create simple Java Project and you can use this tutorial to create web applications too.
First create new project in Eclipse using appropriate name, I’ll give "MyFirstHibernateApp".
You need to manually account for all the needed dependencies, so let’s create new folder called "lib" inside the "MyFirstHibernateApp" by right clicking on it as shown in following Figure 3.
Now copy following files into that folder.
1. hibernate3.jar (Can be found in distribution bundle)
2. All artifacts in the lib/required directory in distribution bundle
3. All artifacts in the lib/jpa directory in distribution bundle
4. All files from either the lib/bytecode/cglib or lib/bytecode/javassist directory
5. One of the slf4j logging (I'll use slf4j-simple-1.6.1.jar found inside slf4j-1.6.1.zip)
6. mysql-connector-java-5.1.15-bin.jar (JDBC driver for MySQL )
2. All artifacts in the lib/required directory in distribution bundle
3. All artifacts in the lib/jpa directory in distribution bundle
4. All files from either the lib/bytecode/cglib or lib/bytecode/javassist directory
5. One of the slf4j logging (I'll use slf4j-simple-1.6.1.jar found inside slf4j-1.6.1.zip)
6. mysql-connector-java-5.1.15-bin.jar (JDBC driver for MySQL )
Then you can configure the built path. To do that, right click on project "MyFirstHibernateApp" in Package Explorer and select Build Path --> Configure Build Path... Then go to Libraries tab and browse lib folder you created earlier. Then add external jars by selecting all jar files that you copied to lib folder in one of previous step. (Check Figure 4).
Now you will be able to see the referenced libraries as follow (Figure 5).
2. Create POJO Classes
Next, I'll create two classes that represent the user and task we want to store in the database. Those are simple JavaBean classes with some properties which uses standard JavaBean naming conventions for property getter and setter methods and private visibility for the fields.
To create new class right click on "MyFirstHibernateApp" and select New --> Class. Then give appropriate package name, I’ll give "com.hib" as figure 6. You can generate getter and setters easily by selecting variable declaration and selecting Source --> Generate Getters and Setters…
User Class
package com.hib; public class User { private Integer id; private String firstName; private String lastName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }Task Class
package com.hib; public class Task { private Integer id; private Integer userID; private String title; private String description; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUserID() { return userID; } public void setUserID(Integer userID) { this.userID = userID; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }The id property holds a unique identifier value for a particular user and task. All persistent entity classes will need such an identifier property if you want to use the full feature set of Hibernate.
3. Create Mapping Files
Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.
Right click on the "src" folder and select New --> File and paste following code there. Save it as user.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"> <hibernate-mapping> <class name="com.hib.User" table="users" > <id name="id" type="int" column="id" > <generator class="native"/> </id> <property name="firstName"> <column name="first_name" /> </property> <property name="lastName"> <column name="last_name"/> </property> </class> </hibernate-mapping>Tasks.java should also have a mapping file, so create another file and paste following code. Save it as task.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"> <hibernate-mapping> <class name="com.hib.Task" table="tasks"> <id name="id" type="int" column="id" > <generator class="native"/> </id> <property name="userID"> <column name="user_id" /> </property> <property name="title"> <column name="title" /> </property> <property name="description"> <column name="description"/> </property> </class> </hibernate-mapping>In the above mapping file you can see the mapping of the unique identifier property to the tables primary key. As we do not want to care about handling this identifier, we configure Hibernate's identifier generation strategy for a surrogate primary key column by giving class="native". If it is not AUTO_INCREMENT one we should use class="assign".
The id element is the declaration of the identifier property. The name="id" mapping attribute declares the name of the JavaBean property and tells Hibernate to use the getId() and setId() methods to access the property. The column attribute tells Hibernate which column of the "users" and "tasks" tables holds the primary key value. Similar to the id element, the name attribute of the property element tells Hibernate which getter and setter methods to use.
4. Hibernate Configuration
Now you have the persistent class and its mapping file in place. Let’s configure Hibernate.
Right click on the "src" folder and select New --> File and paste following code there. Save it as hibernate.cfg.xml. Here you have to give the username and password according to your MySQL account. In my case username is root and there is no password.
<?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> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/userdata</property> <property name="connection.username">root</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.MySQLDialect</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.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">update</property> <!-- Mapping files --> <mapping resource="user.hbm.xml"/> <mapping resource="task.hbm.xml"/> </session-factory> </hibernate-configuration>5. Create Startup Helper Class
You have to startup Hibernate by creating a global org.hibernate.SessionFactory object and storing it somewhere for easy access in your application code. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once. We will create a HibernateUtil helper class that takes care of startup and makes accessing the org.hibernate.SessionFactory more convenient.
To create new class right click on "com.hib" package and select New --> Class and give Name as HibernateUtil.java and paste the following code in class file.
package com.hib; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from 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; } }6. Create Test Class to Load and Store Objects
Now it’s time to do some real work using Hibernate. Following test class illustrate how we can Add, Retrieve, Update and Delete data in a MySQL database.
To create new class right click on "com.hib" package and select New --> Class and give Name as Test.java and paste the following code in class file.
package com.hib; import java.util.Iterator; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; public class Test { /** * @param args */ public static void main(String[] args) { Test tst = new Test(); /** * adding records */ tst.addUser("Saranga", "Rath"); tst.addUser("Isuru", "Sampath"); tst.addUser("Saranga", "Jaya"); tst.addUser("Prasanna", "Milinda"); tst.addTask(1, "Call", "Call Pubudu at 5 PM"); tst.addTask(1, "Shopping", "Buy some foods for Kity"); tst.addTask(2, "Email", "Send birthday wish to Pubudu"); tst.addTask(2, "SMS", "Send message to Dad"); tst.addTask(2, "Office", "Give a call to Boss"); /** * retrieving data */ tst.getFullName("Saranga"); /** * full updating records */ User user = new User(); user.setId(1); user.setFirstName("Saranga"); user.setLastName("Rathnayake"); tst.updateUser(user); /** * partial updating records */ tst.updateLastName(3, "Jayamaha"); /** * deleting records */ User user1 = new User(); user1.setId(4); tst.deleteUser(user1); } private void addUser(String firstName, String lastName) { Transaction trns = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { trns = session.beginTransaction(); User user = new User(); user.setFirstName(firstName); user.setLastName(lastName); session.save(user); session.getTransaction().commit(); } catch (RuntimeException e) { if(trns != null){ trns.rollback(); } e.printStackTrace(); } finally{ session.flush(); session.close(); } } private void addTask(int userID, String title, String description) { Transaction trns = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { trns = session.beginTransaction(); Task task = new Task(); task.setUserID(userID); task.setTitle(title); task.setDescription(description); session.save(task); session.getTransaction().commit(); } catch (RuntimeException e) { if(trns != null){ trns.rollback(); } e.printStackTrace(); } finally{ session.flush(); session.close(); } } private void updateLastName(int id, String lastName) { Transaction trns = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { trns = session.beginTransaction(); String hqlUpdate = "update User u set u.lastName = :newLastName where u.id = :oldId"; int updatedEntities = session.createQuery( hqlUpdate ) .setString( "newLastName", lastName ) .setInteger( "oldId", id ) .executeUpdate(); trns.commit(); } catch (RuntimeException e) { if(trns != null){ trns.rollback(); } e.printStackTrace(); } finally{ session.flush(); session.close(); } } private void updateUser(User user) { Transaction trns = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { trns = session.beginTransaction(); session.update(user); session.getTransaction().commit(); } catch (RuntimeException e) { if(trns != null){ trns.rollback(); } e.printStackTrace(); } finally{ session.flush(); session.close(); } } private void getFullName(String firstName) { Transaction trns = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { trns = session.beginTransaction(); List<User> users = session.createQuery("from User as u where u.firstName = :firstName") .setString( "firstName", firstName ) .list(); for (Iterator<User> iter = users.iterator(); iter.hasNext();) { User user = iter.next(); System.out.println(user.getFirstName() +" " + user.getLastName()); } trns.commit(); } catch (RuntimeException e) { if(trns != null){ trns.rollback(); } e.printStackTrace(); } finally{ session.flush(); session.close(); } } private void deleteUser(User user) { Transaction trns = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { trns = session.beginTransaction(); session.delete(user); session.getTransaction().commit(); } catch (RuntimeException e) { if(trns != null){ trns.rollback(); } e.printStackTrace(); } finally{ session.flush(); session.close(); } } }If you have setup the database and followed the above steps correctly you should get following output.
Hibernate: insert into users (first_name, last_name) values (?, ?) Hibernate: insert into users (first_name, last_name) values (?, ?) Hibernate: insert into users (first_name, last_name) values (?, ?) Hibernate: insert into users (first_name, last_name) values (?, ?) Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?) Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?) Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?) Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?) Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?) Hibernate: select user0_.id as id0_, user0_.first_name as first2_0_, user0_.last_name as last3_0_ from users user0_ where user0_.first_name=? Saranga Rath Saranga Jaya Hibernate: update users set first_name=?, last_name=? where id=? Hibernate: update users set last_name=? where id=? Hibernate: delete from users where id=?Hibernate use Hibernate Query Language (HQL) which is powerful than SQL and fully object-oriented. You can get good knowledge about HQL by following HQL Documentation.
I have included the source files of this tutorial with the database. You can download it from here (Password : sara).
Nice Article.....
ReplyDeleteI'm novel to Hibernate & your post gain me lot of practical knowledge in Hibernate...
I found another article named Introduction to Hibernate which gain the theoritical knowlegde for begginers.....
Great Tutorial.
ReplyDeleteSearched internet for two weeks but was unable to run hibernate using other tutorials but your tutorial got me up and running in just an hour . Thanks
really great tutorial for beginners . I'd highly appreciate to see a post from you for "Integrating Jasypt with Hibernate 3" .
@ Anonymous,
ReplyDeleteThank you for sharing the article.
@ Adil Mukarram,
Thank you very much for your comment. We will try to create a tutorial for that.
nice and easy to learn for beginners
ReplyDeletethanX a Lot for such nice article. It helped me a lot. I searched for days but didn't find any good tutorial using hib with eclipse. :)
ReplyDeleteVery good tutorial!!! I've been looking for something like that for sometime..
ReplyDeleteFor beginners like me I would also add the stage of building the MySQL database and tables:
1. Connect to your account at MySQL.
2. Enter "CREATE DATABASE userdata;"
3. Enter "USE userdata;"
4. Enter "CREATE TABLE users(id int(10) AUTO_INCREMENT, first_name varchar(100), la
st_name varchar(100), primary key(id));
5. ENTER "CREATE TABLE tasks(id int(10) AUTO_INCREMENT, user_id int(10), title varc
har(100), description varchar(100), primary key(id));"
Also, if you need a password to access your MySQL database, you should provide it to the hibernate.cfg.xml file at the line HereShouldComeYourPassWord
Like++. Kudos to you Saranga. The clearest tutorial out there by far. Why couldn't the others make it this simple?
ReplyDelete@ Pondu,
ReplyDeleteThanks for commenting Pondu.
@ babarathotmail,
I'm so happy to hear that. Thanks for commenting.
@ gad.dan,
Thank you very much for your comment. Since I have include the database I didn't put that information in the post.
Next time I'll include it in the post and I updated the post telling about the MySQL password.
@ Anonymous,
Glad I could help brighten your day. :)
i am beginner to hibernate..I tried following the steps but getting the following error:
ReplyDelete12 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.3.0.GA
17 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
20 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
26 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
67 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
67 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
747 [main] INFO org.hibernate.cfg.Configuration - Reading mappings from resource : user.hbm.xml
753 [main] ERROR org.hibernate.util.XMLHelper - Error parsing XML: XML InputStream(1) Premature end of file.
Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource user.hbm.xml
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
at com.hib.HibernateUtil.(HibernateUtil.java:7)
at com.hib.Test.addUser(Test.java:61)
at com.hib.Test.main(Test.java:20)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from resource user.hbm.xml
at org.hibernate.cfg.Configuration.addResource(Configuration.java:602)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1621)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1589)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1568)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1542)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1462)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1448)
at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:11)
... 3 more
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from input stream
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:541)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:599)
... 10 more
Caused by: org.dom4j.DocumentException: Error on line 1 of document : Premature end of file. Nested exception: Premature end of file.
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:532)
... 11 more
@ Neeti,
ReplyDeleteAre you using diffrent package names? Then you have to change the given user.hbm.xml and task.hbm.xml.
And also check the docktype declaration in above mapping files.
(<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">)It should be there.
Thank You !
Hi Neeti,
ReplyDeleteI got the same problem, then i checked the cfg file DOCTYPE ;
the above line has the error, there is a single quote for version and encoding. please change that to double quote's and check once.
all the best. :)
Thanks,
Gangadhar
@ Gangadhar,
ReplyDeleteIt worked for me using single quote's. Anyway thanks for posting the solution. I'll update my post since it is working with double quote's too.
FYI : You have to use a HTML Encoder when you post HTML codes in blogger, otherwise blogger will not be able to show them.
Thank You !
Antonio:
ReplyDeleteI was already in other two examples without success .. read some books and nothing
Really great info!!! It helped me a lot.. Thanks!!
:)
@ Le Unamme,
ReplyDeleteGlad I could help brighten your day, Thanks for commenting.
Thanks !
Hello! Very good manual? thanx )
ReplyDeleteBut when the application start, I have an error:
2169 [main] WARN org.hibernate.cfg.SettingsFactory - Could not obtain connection to query metadata
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Could you help me? plz?
@ Mihail,
ReplyDeleteCan you post full error you are getting?
Please check whether you are giving correct username and password to MYSQL in hibernate.cfg.xml file. Check whether you are giving correct path to it. Didn't you try downloading my project ?
Thank You !
Ganesh : Facing some problem with error
ReplyDeleteINFO: Configuration resource: hibernate.cfg.xml
Initial SessionFactory creation failed.org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:15)
at com.hib.HibernateUtil.(HibernateUtil.java:6)
at com.hib.Test.addUser(Test.java:60)
at com.hib.Test.main(Test.java:19)
Caused by: org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1494)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1428)
at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:10)
... 3 more
Caused by: org.dom4j.DocumentException: Connection refused: connect Nested exception: Connection refused: connect
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1484)
... 5 more
I'm getting error in session.getTransaction() ..help me to resolve it
ReplyDeleteThank you! this is a very good post for starting it off!
ReplyDelete@ test,
ReplyDeleteCheck whether your hibernate.cfg.xml file is in the correct place.
Thanks !
@ saranraju,
ReplyDeleteCan you post the full error. Thanks !
@ Dalen,
Glad I could help brighten your day. Thanks for commenting.
Thank you very much! this is a very useful post
ReplyDeleteThanks for the article. I always feel starting with an example helps a lot in core concepts.
ReplyDeleteHi i am constantly getting the same error
ReplyDeleteat org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at com.hib.Test.addUser(Test.java:79)
at com.hib.Test.main(Test.java:20)
Can some body please help me
It is very nice example in hibernate, easy to understand. please continue to write other practicales so that we can familiar with hibernate.
ReplyDeleteThank you so much.
Thank you very much! But encountered the same error "Neeti"
ReplyDelete(
287 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
298 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.6.8.Final
...
)
I'm checked hibernate.cfg.xml file but not fix. Can you share project of Eclipse for tutorial. Thanks from Viet Nam!
@ Unknown,
ReplyDeleteI have shared the project and you can download it from the link given at the end of the post.
Thanks !
nice dear,it is really good for beginners......
ReplyDelete@ amit kumar singh,
ReplyDeleteYou are welcome...
thanks for posting tutorial for beginners..
ReplyDeleteBut i am not able to run it successfully.
I am getting following error :
org.hibernate.exception.JDBCConnectionException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:99)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:160)
at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:81)
at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1473)
at com.hib.Test.addUser(Test.java:63)
at com.hib.Test.main(Test.java:20)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
at com.mysql.jdbc.MysqlIO.(MysqlIO.java:344)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2332)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2369)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2153)
at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:792)
at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:133)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
... 6 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.(Unknown Source)
at java.net.Socket.(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:257)
at com.mysql.jdbc.MysqlIO.(MysqlIO.java:294)
... 22 more
--------------------------------------------
Please suggest me the solution ...
hibernate.cfg.xml file is ....
com.mysql.jdbc.Driver
jdbc:mysql://localhost/kgtest
root
MyNewPass
1
org.hibernate.dialect.MySQLDialect
thread
org.hibernate.cache.NoCacheProvider
true
update
great article.. just the way i wanted it :)
ReplyDeletei faces the problem for the creating the hibernate for that i post the question on stackoverflow and link is given below
ReplyDeletehttp://stackoverflow.com/questions/9084087/error-for-the-creating-the-hibernate
please try to solve my problem.
@ SatyAnveshak,
ReplyDeletePlease make sure database is up and running.
@ rakshitha,
You are welcome !
@ Nimit,
There is no error here. Please describe your problem.
Sara,
ReplyDeleteI'm getting the following error. Could you please help?
Feb 3, 2012 1:50:03 PM org.hibernate.annotations.common.Version
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Feb 3, 2012 1:50:04 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.0.1.Final}
Feb 3, 2012 1:50:04 PM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
Feb 3, 2012 1:50:04 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Feb 3, 2012 1:50:04 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Feb 3, 2012 1:50:04 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Feb 3, 2012 1:50:04 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: user.hbm.xml
Feb 3, 2012 1:50:04 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: task.hbm.xml
Feb 3, 2012 1:50:04 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource user.hbm.xml
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.lib.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
at com.lib.HibernateUtil.(HibernateUtil.java:7)
at com.lib.Test.addUser(Test.java:61)
at com.lib.Test.main(Test.java:20)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from resource user.hbm.xml
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3380)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXmlQueue(Configuration.java:3369)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3357)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1334)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1724)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1775)
at com.lib.HibernateUtil.buildSessionFactory(HibernateUtil.java:11)
... 3 more
Caused by: org.hibernate.MappingException: class com.hib.User not found while looking for property: firstName
at org.hibernate.internal.util.ReflectHelper.reflectedPropertyClass(ReflectHelper.java:232)
at org.hibernate.mapping.SimpleValue.setTypeUsingReflection(SimpleValue.java:314)
at org.hibernate.cfg.HbmBinder.createProperty(HbmBinder.java:2247)
at org.hibernate.cfg.HbmBinder.createClassProperties(HbmBinder.java:2224)
at org.hibernate.cfg.HbmBinder.createClassProperties(HbmBinder.java:2114)
at org.hibernate.cfg.HbmBinder.bindRootPersistentClassCommonValues(HbmBinder.java:405)
at org.hibernate.cfg.HbmBinder.bindRootClass(HbmBinder.java:320)
at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:171)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3377)
... 9 more
Caused by: java.lang.ClassNotFoundException: com.hib.User
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.hibernate.internal.util.ReflectHelper.classForName(ReflectHelper.java:192)
at org.hibernate.internal.util.ReflectHelper.reflectedPropertyClass(ReflectHelper.java:228)
... 17 more
Saranga,
ReplyDeleteHave you got a chance to take a look at the error in my previous post?
Thanks a lot!
Wei
@ Wei,
ReplyDeleteSorry for the late reply.
Please double check your "user.hbm.xml" file. Check whether you have set the class attribute correctly with package.
e.g. class name="com.hib.User" table="users"
Did you try downloading my code ?
Thank You !
Great tutorial
ReplyDeleteI tried running it and came across a problem I am unable to solve.
I am getting the following failure:
Initial SessionFactory creation failed.org.hibernate.HibernateException: could not instantiate RegionFactory [org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge]
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
at com.hib.HibernateUtil.(HibernateUtil.java:7)
at com.hib.Test.addUser(Test.java:61)
at com.hib.Test.main(Test.java:20)
Caused by: org.hibernate.HibernateException: could not instantiate RegionFactory [org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge]
at org.hibernate.cfg.SettingsFactory.createRegionFactory(SettingsFactory.java:423)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:280)
at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2833)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2829)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1840)
at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:11)
... 3 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.hibernate.cfg.SettingsFactory.createRegionFactory(SettingsFactory.java:409)
... 8 more
Caused by: org.hibernate.cache.CacheException: could not instantiate CacheProvider [org.hibernate.cache.internal.NoCacheProvider]
at org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge.(RegionFactoryCacheProviderBridge.java:66)
... 13 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.cache.internal.NoCacheProvider
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.hibernate.util.ReflectHelper.classForName(ReflectHelper.java:192)
at org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge.(RegionFactoryCacheProviderBridge.java:63)
... 13 more
Seems the the code falls on :
return new Configuration().configure().buildSessionFactory();
Any ideas as to what it may be?
Best wishes,
CK
having same problem...
DeleteI see what to do up to fig.4. Fig 4 has what looks to be a library icon and not a plain folder icon. What instructions give this type of icon?
ReplyDeletethanks,
Matias
Hi Matias,
DeleteSorry, there was an issue with the order of images, Please check it now.
Thanks !
how to execute this program.when i execute this program then null pointer exception is coming.
ReplyDeleteSorry for the late reply. Did you able to fix this? What was the issue ?
DeleteHi,I downloaded the distribution bundle,but i cannot find the file 'hibernate3.zip' in it,as you have mentioned to copy it in the lib folder of my project.The distribution bundle that i downloaded is 'hibernate-release-4.1.0.Final'.
ReplyDeleteDid you able to find it? It should be there.
DeleteReally a helpful article for Begineers.
ReplyDeleteThanks for commenting...
DeleteHai. Nice tutorial.
ReplyDeleteVery nice article .... thank you
ReplyDeleteYou are welcome...
Deletehi I am Amit Pathak
ReplyDeletethis very good article for beginners
I am getting following error while executing the code....
plz help me
Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
at com.hib.HibernateUtil.(HibernateUtil.java:7)
at com.hib.Test.addUser(Test.java:64)
at com.hib.Test.main(Test.java:23)
Caused by: java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.hibernate.cfg.Configuration.(Configuration.java:110)
at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:11)
... 3 more
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 5 more
Thanks man, Your article is really helpful
ReplyDeleteThis is great mate, thanks heaps for this great tutorial. Cheers from New Zealand.
ReplyDeleteI have used oracle database instead of mysql and I have changed code according to oracle whereever it is required.
ReplyDeleteMy hibernate.cfg.xml is as following:
oracle.jdbc.driver.OracleDriver
jdbc:oracle:thin:@172.20.46.54:1521:entmon
emon
emon
1
org.hibernate.dialect.oracle10gdialect
thread
org.hibernate.cache.NoCacheProvider
true
update
and it's throwing following exception when I ran Test.java class
Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:17)
at com.hib.HibernateUtil.(HibernateUtil.java:8)
at com.hib.Test.addUser(Test.java:61)
at com.hib.Test.main(Test.java:20)
Caused by: java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.hibernate.cfg.Configuration.(Configuration.java:117)
at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:12)
... 3 more
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 5 more
Very nice article .... thank you!!
ReplyDeleteI'm getting the following failure:
Grave: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/InvalidMappingException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
...
Caused by: java.lang.NoClassDefFoundError: org/hibernate/InvalidMappingException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2404)
at java.lang.Class.getConstructor0(Class.java:2714)
at java.lang.Class.getDeclaredConstructor(Class.java:2002)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:104)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newConfiguration(LocalSessionFactoryBean.java:818)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:549)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
... 42 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.InvalidMappingException
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1711)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556)
... 52 more
Do you have any idea??
Thanks!!
org.hibernate.InvalidMappingException: Unable to read XML
ReplyDeleteat org.hibernate.util.xml.MappingReader.readMappingDocument(MappingReader.java:101)
at org.hibernate.cfg.Configuration.add(Configuration.java:513)
at org.hibernate.cfg.Configuration.add(Configuration.java:509)
at org.hibernate.cfg.Configuration.add(Configuration.java:716)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:801)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2344)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2310)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2290)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2243)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2158)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2137)
at InsertTest.main(InsertTest.java:13)
Caused by: org.dom4j.DocumentException: Error on line 16 of document : The element type "class" mus
t be terminated by the matching end-tag "". Nested exception: The element type "class" must
be terminated by the matching end-tag "".
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.util.xml.MappingReader.readMappingDocument(MappingReader.java:75)
... 11 more
Exception in thread "main" java.lang.NullPointerException
at InsertTest.main(InsertTest.java:38)
Thanks for providing this tutorial.
ReplyDeleteThanks for everything , but i got this fault event when i use MXML with this tutorial :
ReplyDeleteReceived fault: [RPC Fault faultString="org/hibernate/Session" faultCode="Server.Processing" faultDetail="null"]
can you help me with that ?
Good post!
ReplyDeletethanks yaar...that was a good one..
ReplyDeleteHello, first thanks for your tutorial, it's very practical. I'll mention it in my blog.
ReplyDeleteSecond, I've found some errors, while putting this exercise.
1.-I found the solution. I add JPA jar (i got an exception about this).
The exception was: Exception in thread “main” java.lang.NoClassDefFoundError: javax/persistence/EntityListeners
2.-I put it a default value in my keys in mysql (I had an exception with this).
3.-I am having an exception, I've read that I can use
but it still doesn't work.
Here is the exception
Hibernate: insert into users (first_name, last_name) values (?, ?)
org.hibernate.HibernateException: The database returned no natively generated identity value
at org.hibernate.id.IdentifierGeneratorHelper.getGeneratedIdentity(IdentifierGeneratorHelper.java:86)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:97)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:56)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2346)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2853)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at
I give realized.... my keys have to be AUTO-INCREMENT .....
ReplyDeleteIn Database config config settings you have missed the port number.
ReplyDeletejdbc:mysql://localhost:PORT-NO/userdata
Thanks.
excellent tutorial for the beginners ... thanks alot
ReplyDeleteHi!
ReplyDeleteThe first time that i run the application everything is ok!
The second time I face that problem(exception)....
Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:85)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:70)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:90)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:189)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at com.hib.Test.deleteUser(Test.java:186)
at com.hib.Test.main(Test.java:55)
1257 [main] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:85)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:70)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:90)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:189)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at com.hib.Test.deleteUser(Test.java:186)
at com.hib.Test.main(Test.java:55)
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:85)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:70)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:90)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:189)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at com.hib.Test.deleteUser(Test.java:186)
at com.hib.Test.main(Test.java:55)
hi,
ReplyDeletei'm using Jboss, hibernate3 and ejb 2.x ... i got error while run my module.
ERROR [org.jboss.ejb.plugins.LogInterceptor] Unexpected Error in method: public abstract java.lang.Object utils.cs.CommonSearch.getRecordsByJDlgId(java.lang.String) throws java.rmi.RemoteException
java.lang.NoClassDefFoundError: Could not initialize class utils.cs.HibernateUtil
at utils.cs.CommonSearchBean.getRecordsByJDlgId(CommonSearchBean.java:560)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.invocation.Invocation.performCall(Invocation.java:359)
at org.jboss.ejb.StatelessSessionContainer$ContainerInterceptor.invoke(StatelessSessionContainer.java:237)
at org.jboss.resource.connectionmanager.CachedConnectionInterceptor.invoke(CachedConnectionInterceptor.java:158)
at org.jboss.ejb.plugins.StatelessSessionInstanceInterceptor.invoke(StatelessSessionInstanceInterceptor.java:169)
at org.jboss.ejb.plugins.CallValidationInterceptor.invoke(CallValidationInterceptor.java:63)
at org.jboss.ejb.plugins.AbstractTxInterceptor.invokeNext(AbstractTxInterceptor.java:121)
at org.jboss.ejb.plugins.TxInterceptorCMT.runWithTransactions(TxInterceptorCMT.java:350)
at org.jboss.ejb.plugins.TxInterceptorCMT.invoke(TxInterceptorCMT.java:181)
at org.jboss.ejb.plugins.SecurityInterceptor.invoke(SecurityInterceptor.java:168)
at org.jboss.ejb.plugins.LogInterceptor.invoke(LogInterceptor.java:205)
at org.jboss.ejb.plugins.ProxyFactoryFinderInterceptor.invoke(ProxyFactoryFinderInterceptor.java:138)
at org.jboss.ejb.SessionContainer.internalInvoke(SessionContainer.java:648)
at org.jboss.ejb.Container.invoke(Container.java:960)
at sun.reflect.GeneratedMethodAccessor364.invoke(Unknown Source)
I'm getting the following failure:
ReplyDeleteException in thread "main" java.lang.NoClassDefFoundError: HibernateTestCase
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
ReplyDeletelog4j:WARN Please initialize the log4j system properly.
Hibernate: insert into users (first_name, last_name) values (?, ?)
org.hibernate.exception.GenericJDBCException: could not insert: [com.hib.User]
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:40)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2108)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2588)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:290)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:180)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:108)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:186)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:175)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
at com.hib.Test.addUser(Test.java:70)
at com.hib.Test.main(Test.java:20)
Caused by: java.sql.SQLException: Could not retrieve transation read-only status server
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:951)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:941)
at com.mysql.jdbc.ConnectionImpl.isReadOnly(ConnectionImpl.java:3936)
at com.mysql.jdbc.ConnectionImpl.isReadOnly(ConnectionImpl.java:3907)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2408)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33)
... 17 more
Caused by: java.sql.SQLException: Unknown system variable 'tx_read_only'
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4187)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4119)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2809)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2758)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1612)
at com.mysql.jdbc.ConnectionImpl.isReadOnly(ConnectionImpl.java:3930)
... 23 more
A quick guide !!
ReplyDelete