You can view and download the complete source code of this tutorial from my github account.
In this tutorial, we will create a simple CRUD (Create Read Update Delete) User Management Console Application using Java, Hibernate and MySQL.
For this tutorial, we will need the following tools: (The older or newer version should also works).
1. Eclipse IDE for Java EE Developers (Indigo – ver. 3.7)
2. MySQL Community Server and MySQL Workbench (GUI Tool)
First, lets create the database and table for User using the following SQL scripts. Copy and run this script in the MySQL Workbench (GUI Tool) –> SQL Editor:
create database UserDB; use UserDB; grant all on UserDB.* to 'admin'@'localhost' identified by 'test'; CREATE TABLE UserDB.`users` ( `userid` int(11) NOT NULL AUTO_INCREMENT, `firstname` varchar(45) DEFAULT NULL, `lastname` varchar(45) DEFAULT NULL, `dob` date DEFAULT NULL, `email` varchar(100) DEFAULT NULL, PRIMARY KEY (`userid`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8
Go to eclipse and create a new project. Select File—>New—>Java Project. Enter “SimpleJava Hibernate” as the project name. Accept all the default value. Click Finish.
Please refer to this project directory in case you miss something along the way
After creating the project, we need to add MySQL connector .jar file to our project build path. To do so, right click our newly created project “SimpleJavaHibernate” and choose Properties to open Properties window.
Select Java Build Path in the left side tree view to open right side detail view. Click Add External JARs.. button to open File browser dialog and point it to the MySQL connector .jar file which you have downloaded earlier.
Furthermore, we need to add Hibernate library to our project. Right click again the project and select Properties –>Java Build Path. This time, click Add Library. Select User Library from the list of selection. Click User Library. Next, click New. Enter “Hibernate” as the library name. Ok. Click our newly created User Library and click Add Jar. Select all the .jar file in both provided and required folder which located inside this directory structure [your hibernate download folder]—>hibernate-search-4.1.0.CR3-dist—>hibernate-search-4.1.0.CR3—>dist—>lib
Verify your build path to match configuration in picture below:
This is all the configuration that we need to do and now let us get to the code.
Create four packages in the src folder.
- com.daniel: contains the main method as the entry point for our console application
- com.daniel.dao: contains the logic for database operation
- com.daniel.model: contains the POJO (Plain Old Java Object). Each class in this package represents the database table. For this tutorial, however, we only have one table.
- com.daniel.util : contains the class for initiating database connection
Next, create a new Java class. in com.daniel.model folder. Name it “User.java” and insert these following codes. Each of the variables in this class represents the field in USERS table in our database.
package com.daniel.model; import java.util.Date; public class User { private int userid; private String firstName; private String lastName; private Date dob; private String email; public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } 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; } public Date getDob() { return dob; } public void setDob(Date dob) { this.dob = dob; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User [userid=" + userid + ", firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + ", email=" + email + "]"; } }
Create a new class in com.daniel.util package and name it HibernateUtil.java. This class will read the configuration in our hibernate.cfg.xml file which handles the database connection to our MySQL server.
package com.daniel.util; 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; } }
Create the aforementioned hibernate.cfg.xml configuration file directly under SimpleJavaHibernate folder. Put the following information inside.
<?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/UserDB</property> <property name="connection.username">admin</property> <property name="connection.password">test</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" /> </session-factory> </hibernate-configuration>
Notice that inside the file, there is an information about mapping resource which point to user.hbm.xml file. So, create an .xml file directly under SimpleJavaHibernate folder to map our Plain Old Java Object (POJO) variables with fields in database. Name it user.hbm.xml and write the following code inside
<?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.daniel.model.User" table="users"> <id name="userid" type="int" column="userid"> <generator class="increment" /> </id> <property name="firstName"> <column name="firstname" /> </property> <property name="lastName"> <column name="lastname" /> </property> <property name="dob"> <column name="dob" /> </property> <property name="email"> <column name="email" /> </property> </class> </hibernate-mapping>
Next, create a new class in com.daniel.dao package, name it UserDao.java. Dao stands for Data Access Object. It contains the logic for database operation.
package com.daniel.dao; import java.util.ArrayList; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.daniel.model.User; import com.daniel.util.HibernateUtil; public class UserDao { public void addUser(User user) { Transaction trns = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { trns = session.beginTransaction(); session.save(user); session.getTransaction().commit(); } catch (RuntimeException e) { if (trns != null) { trns.rollback(); } e.printStackTrace(); } finally { session.flush(); session.close(); } } public void deleteUser(int userid) { Transaction trns = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { trns = session.beginTransaction(); User user = (User) session.load(User.class, new Integer(userid)); session.delete(user); session.getTransaction().commit(); } catch (RuntimeException e) { if (trns != null) { trns.rollback(); } e.printStackTrace(); } finally { session.flush(); session.close(); } } public 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(); } } public List<User> getAllUsers() { List<User> users = new ArrayList<User>(); Transaction trns = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { trns = session.beginTransaction(); users = session.createQuery("from User").list(); } catch (RuntimeException e) { e.printStackTrace(); } finally { session.flush(); session.close(); } return users; } public User getUserById(int userid) { User user = null; Transaction trns = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { trns = session.beginTransaction(); String queryString = "from User where id = :id"; Query query = session.createQuery(queryString); query.setInteger("id", userid); user = (User) query.uniqueResult(); } catch (RuntimeException e) { e.printStackTrace(); } finally { session.flush(); session.close(); } return user; } }
Finally, create our main application class inside the com.daniel package and name it App.java
package com.daniel; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.daniel.dao.UserDao; import com.daniel.model.User; import com.daniel.util.DbUtil; public class App { public static void main(String[] args) { UserDao dao = new UserDao(); // Add new user User user = new User(); user.setFirstName("Daniel"); user.setLastName("NikoJdbc"); try { Date dob = new SimpleDateFormat("yyyy-MM-dd").parse("1986-01-02"); user.setDob(dob); } catch (ParseException e) { e.printStackTrace(); } user.setEmail("daniel@example.com"); dao.addUser(user); // // // Update user user.setEmail("daniel@updatedJdbc.com"); user.setUserid(1); dao.updateUser(user); // Delete user //dao.deleteUser(2); // Get all users for (User iter : dao.getAllUsers()) { System.out.println(iter); } // Get user by id System.out.println(dao.getUserById(8)); try { DbUtil.getConnection().close(); } catch (SQLException e) { e.printStackTrace(); } } }
That is it. Run the project from eclipse and see the output from Console window
Not sure if I’m missing something but is there not suppose to be a com.daniel.util.DbUtil Class?
make this code in comment /* try {
DbUtil.getConnection().close();
} catch (SQLException e) {
e.printStackTrace();
}*/
//import com.daniel.util.DbUtil;
and that will works
Hello all beginners today i am telling you a CRUD example in hibernate by which you can be make a small example until you make a expert.
By this example you got some knowledge of HQL (Hibernate Query Language).
If you’re novice in Hibernate then this example obviously help you to understand them.
alert(“hello”);
window.open(\”http://www.dasnic.com\”,\”_self\”);
Hi to all…
you are correct Mr.Casey Pledger.You have not created a package named com.danial.util.DbUtil. but you used that package.please give me a solution to get rid of this issue with your pjt…..
when i compile your code am getting the following error…
Initial SessionFactory creation failed.java.lang.ExceptionInInitializerError
Exception in thread “main” java.lang.ExceptionInInitializerError
at com.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:18)
at com.util.HibernateUtil.(HibernateUtil.java:9)
at com.DAO.UserDao.addUser(UserDao.java:17)
at com.controller.App.main(App.java:28)
Caused by: java.lang.ExceptionInInitializerError
at com.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:14)
… 3 more
Caused by: org.apache.commons.logging.LogConfigurationException: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException) (Caused by org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException))
at org.apache.commons.logging.impl.LogFactoryImpl.newInstance(LogFactoryImpl.java:543)
at org.apache.commons.logging.impl.LogFactoryImpl.getInstance(LogFactoryImpl.java:235)
at org.apache.commons.logging.impl.LogFactoryImpl.getInstance(LogFactoryImpl.java:209)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:351)
at org.hibernate.cfg.Configuration.(Configuration.java:120)
… 4 more
Caused by: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException)
at org.apache.commons.logging.impl.LogFactoryImpl.getLogConstructor(LogFactoryImpl.java:397)
at org.apache.commons.logging.impl.LogFactoryImpl.newInstance(LogFactoryImpl.java:529)
… 8 more
Caused by: java.lang.NullPointerException
at org.apache.commons.logging.impl.LogFactoryImpl.getLogConstructor(LogFactoryImpl.java:374)
… 9 more
Was super excited about this tutorial….. and now what a waste of time. Incomplete, DO NOT WASTE YOUR TIME
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Initial SessionFactory creation failed.org.hibernate.HibernateException: Could not parse configuration: /hibernate.cfg.xml
Exception in thread “main” java.lang.ExceptionInInitializerError
at com.daniel.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
at com.daniel.util.HibernateUtil.(HibernateUtil.java:7)
at com.daniel.dao.UserDao.addUser(UserDao.java:17)
at com.daniel.App.main(App.java:28)
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 org.hibernate.cfg.Configuration.configure(Configuration.java:1414)
at com.daniel.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:12)
… 3 more
Caused by: org.dom4j.DocumentException: Connection timed out: connect Nested exception: Connection timed out: connect
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1484)
… 6 more
Muchas gracias por su aporte, me ha sido muy util en un proyecto de la universidad.
Solo que este era en Sql Server. Lo único que modifique fue el tipo de conexión con su correspondiente driver y lo trabajé en NetBeanst.
Nuevamente gracias,
Thanks
Hello,
I’ve made some modification’s and make this program working. As project structure, does not show DbUtil Class, so dont try to use it, instead make a modification’s like below (or of your own logic/choice). Hope this will be helpful.
App.java:
package com.daniel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.daniel.dao.UserDao;
import com.daniel.model.User;
import com.daniel.util.HibernateUtil;
public class App {
public static void main(String[] args) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
UserDao dao = new UserDao();
// Add new user
User user = new User();
user.setFirstName(“Daniel”);
user.setLastName(“NikoJdbc”);
try {
Date dob = new SimpleDateFormat(“yyyy-MM-dd”).parse(“2014-05-13”);
user.setDob(dob);
} catch (ParseException e) {
e.printStackTrace();
}
user.setEmail(“prateek@example.com”);
dao.addUser(user);
System.out.println(“User is added successfully into DB”);
user.setEmail(“prateek@itcompany.com”);
user.setUserid(1);
dao.updateUser(user);
System.out.println(“User is updated successfully”);
// Delete user
//dao.deleteUser(2);
// Get all users
for (User iter : dao.getAllUsers()) {
System.out.println(iter);
}
// Get user by id
System.out.println(dao.getUserById(8));
session.getTransaction().commit();
session.save(user);
session.close();
}
}
Also made some minor modification’s at User.java class (not required to make a program runnable)
The O/p, I get on console
Hibernate: drop table if exists USER
Hibernate: create table USER (USER_ID integer not null auto_increment, DOB date, EMAIL varchar(255), FIRST_NAME varchar(255), LAST_NAME varchar(255), primary key (USER_ID))
Hibernate: insert into USER (DOB, EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?, ?)
User is added successfully into DB
Hibernate: update USER set DOB=?, EMAIL=?, FIRST_NAME=?, LAST_NAME=? where USER_ID=?
User is updated successfully
Hibernate: select user0_.USER_ID as USER1_0_, user0_.DOB as DOB0_, user0_.EMAIL as EMAIL0_, user0_.FIRST_NAME as FIRST4_0_, user0_.LAST_NAME as LAST5_0_ from USER user0_
User [userid=1, firstName=Daniel, lastName=NikoJdbc, dob=2014-05-13, email=prateek@itcompany.com]
Hibernate: select user0_.USER_ID as USER1_0_, user0_.DOB as DOB0_, user0_.EMAIL as EMAIL0_, user0_.FIRST_NAME as FIRST4_0_, user0_.LAST_NAME as LAST5_0_ from USER user0_ where user0_.USER_ID=?
null
Hibernate: insert into USER (DOB, EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?, ?)
O/P from MySql:
mysql> select * from User;
+———+————+———————–+————+———–+
| USER_ID | DOB | EMAIL | FIRST_NAME | LAST_NAME |
+———+————+———————–+————+———–+
| 1 | 2014-05-13 | prateek@itcompany.com | Daniel | NikoJdbc |
+———+————+———————–+————+———–+
1 row in set (0.00 sec)
great work danial .who one not like this tutorial they have not at all knowledge about hibernate…
Hi Friends,
I did some modifications to the above application and it run successfully,
Just you need to remove DbUtil.getConnection() from the application,then it works fine.
And here in user.hbm.xml used generator class ‘increment’ ,so when ever you are updating the record,then you don’t need give setUserId().Other wise it give an Exception like org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1. That’s all Friends…
Bonjour suis debut en JEE j’ai testé le code CRUD l’ajout modifier et supprimmé sa marche, maintenant je veux créer une petite application je me suis confronté a des problemes , j’ai deux tables fournisseur et materiel la clé de table fournisseur migré (clé etrangér ) dans la materiel ,comment recuperé la clé etrangér dans la page JSP (select) , et le deuxiem blem j’ai vu la methode de la recherche dans la classe dao mais je sais pas comment le faire dans une page jsp , s’il te plait si quelqu’un peut m’aider
Doesn’t work for me author didnt show it step by step it’s just retarded.
Thank You ….Your tutorial helped me to learn hibernate practically……….
can we have the same example with for hibernate crud with jsp and servlet
Another half baked, non real world example.
Where could I create a table if I do not have access to SQL workbench?
Great article, nice and clean code. I usually prefer using maven to avoid jar hell particularly with hibernate.
I wrote a platform to generate complete CRUD using Spring, Hibernate, Angular amongst other technologies. check it out at http://www.scaffoldthis.com.
am getting null in table y?????
I see you don’t monetize your website, don’t waste your traffic,
you can earn additional cash every month because you’ve got hi quality
content. If you want to know how to make extra money, search for:
Boorfe’s tips best adsense alternative
you can find a good example here with a video
http://tutoriauxjee.blogspot.com/2015/02/hibernate-crud.html
In the hibernate.cfg.xml I use this.
com.mysql.jdbc.Driver
update
jdbc:mysql://localhost:3306/db_test
root
10
true
org.hibernate.dialect.MySQL5Dialect
thread
And in pom.xml use this (with lombok for getter and setter)
org.hibernate
hibernate-core
5.2.12.Final
mysql
mysql-connector-java
5.1.16
org.projectlombok
lombok
1.16.20
provided
junit
junit
3.8.1
test
And in the file HibernateUtil use:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure(“hibernate.cfg.xml”).build();
Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
} catch (Throwable th) {
System.err.println(“Enitial SessionFactory creation failed” + th);
throw new ExceptionInInitializerError(th);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
And to finish, in the main I put this to open and close connections
public class App {
public static void main(String[] args) {
SessionFactory sessFact = null;
try {
sessFact = HibernateUtil.getSessionFactory();
Session session = sessFact.getCurrentSession();
Transaction tr = session.beginTransaction();
tr.commit();
sessFact.close();
} catch (Exception ex) {
if (sessFact != null) {
sessFact.close();
}
}
}
}
In the hibernate.cfg.xml I use this.
(?xml version=’1.0′ encoding=’utf-8′?)
(!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD//EN”
“http://hibernate.sourceforge.net/hibernate-configuration-5.0.dtd”)
(hibernate-configuration)
(session-factory)
(property name=”hibernate.connection.driver_class”)com.mysql.jdbc.Driver/property>
update
(property name=”hibernate.connection.url”>jdbc:mysql://localhost:3306/db_test
(property name=”hibernate.connection.username”>root
(property name=”hibernate.connection.password”>
(property name=”hibernate.connection.pool_size”>10
(property name=”show_sql”>true
(property name=”dialect”>org.hibernate.dialect.MySQL5Dialect
(property name=”hibernate.current_session_context_class”>thread
(mapping class=”models.Car” />
(/session-factory>
(/hibernate-configuration>
And in pom.xml use this (with lombok for getter and setter)
(dependencies>
(dependency>
(groupId>org.hibernate/groupId>
(artifactId>hibernate-core/artifactId>
(version>5.2.12.Final/version>
/dependency>
(dependency>
(groupId>mysql/groupId>
(artifactId>mysql-connector-java/artifactId>
(version>5.1.16/version>
/dependency>
(dependency>
(groupId>org.projectlombok/groupId>
(artifactId>lombok/artifactId>
(version>1.16.20/version>
(scope>provided/scope>
/dependency>
(dependency>
(groupId>junit/groupId>
(artifactId>junit/artifactId>
(version>3.8.1/version>
(scope>test/scope>
(/dependency>
(/dependencies>
And in the file HibernateUtil use:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure(“hibernate.cfg.xml”).build();
Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
} catch (Throwable th) {
System.err.println(“Enitial SessionFactory creation failed” + th);
throw new ExceptionInInitializerError(th);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
And to finish, in the main I put this to open and close connections
public class App {
public static void main(String[] args) {
SessionFactory sessFact = null;
try {
sessFact = HibernateUtil.getSessionFactory();
Session session = sessFact.getCurrentSession();
Transaction tr = session.beginTransaction();
tr.commit();
sessFact.close();
} catch (Exception ex) {
if (sessFact != null) {
sessFact.close();
}
}
}
}