CREATE TABLE `employee` (
`id` BIGINT(10) NOT NULL AUTO_INCREMENT,
`firstname` VARCHAR(50) NULL DEFAULT NULL,
`lastname` VARCHAR(50) NULL DEFAULT NULL,
`birth_date` DATE NOT NULL,
`cell_phone` VARCHAR(15) NOT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=606
Code language: SQL (Structured Query Language) (sql)
Thus, following will be the connection string to connect with MySQL. Connection URL: jdbc:mysql://localhost:3306/tutorial
DB Username: root
DB Password: <your mysql password>
Code language: JavaScript (javascript)
mvn archetype:generate \
-DgroupId=net.viralpatel.hibernate \
-DartifactId=HibernateHelloWorldXML \
-DarchetypeArtifactId=maven-archetype-quickstart \
-DinteractiveMode=false
Code language: Java (java)
Once you execute above command, a project “HibernateHelloWorldXML” is created. Note that this is a Java project which already has folder structures compatible to Maven. Once this is done, we will convert it to be compatible with Eclipse. For that executes following command on command prompt. Code language: Java (java)mvn eclipse:eclipse
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.viralpatel.hibernate</groupId>
<artifactId>HibernateHelloWorldXML</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>HibernateHelloWorldXML</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.10</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.6.ga</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Code language: HTML, XML (xml)
Once we have added these dependencies, we will execute following command so that maven will download required Jar files and add the same to eclipse classpath. The above step is not mandatory. If you have Maven plugin for Eclipse installed in your IDE (Latest eclipse comes with this plugin built-in) you can just enable Maven dependencies by doing Right click on project > Maven > Enable Dependency Management.Code language: Java (java)mvn eclipse:eclipse
<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/tutorial</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">false</property>
<property name="hbm2ddl.auto">validate</property>
<mapping resource="net/viralpatel/hibernate/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Code language: HTML, XML (xml)
One thing we need to make sure in Eclipse is that the Java build path must reflect **/*.xml. Right click on project > Properties > Java Build Path > Source > Add **/*.xml as follow: package net.viralpatel.hibernate;
import java.sql.Date;
public class Employee {
private Long id;
private String firstname;
private String lastname;
private Date birthDate;
private String cellphone;
public Employee() {
}
public Employee(String firstname, String lastname, Date birthdate, String phone) {
this.firstname = firstname;
this.lastname = lastname;
this.birthDate = birthdate;
this.cellphone = phone;
}
// Getter and Setter methods
}
Code language: Java (java)
Above is the Employee POJO class that we will use to fetch data from Employee table. This Java class will be mapped by Hiberate with Employee table. Note that we have define two constructors first default and second with arguements. The second constructor is optional. But note that you must define a default (No-arguement) constructor in your mapping class. File: /src/main/java/net/viralpatel/hibernate/HibernateUtil.java package net.viralpatel.hibernate;
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) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Code language: Java (java)
As discussed in previous article Introduction to Hibernate framework, we have to create SessionFactory instance in order to communicate with Database in Hibernate. We will use a Utility class called HibernateUtil to instantiate SessionFactory. File: /src/main/java/net/viralpatel/hibernate/Employee.hbm.xml <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="net.viralpatel.hibernate">
<class name="Employee" table="EMPLOYEE">
<id name="id" column="ID">
<generator class="native"/>
</id>
<property name="firstname" />
<property name="lastname" column="lastname"/>
<property name="birthDate" type="date" column="birth_date"/>
<property name="cellphone" column="cell_phone"/>
</class>
</hibernate-mapping>
Code language: HTML, XML (xml)
private static Employee save(Employee employee) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Long id = (Long) session.save(employee);
employee.setId(id);
session.getTransaction().commit();
session.close();
return employee;
}
...
...
...
// Call the save() method to insert a record in database.
System.out.println("******* WRITE *******");
Employee empl = new Employee("Jack", "Bauer", new Date(System.currentTimeMillis()), "911");
empl = save(empl);
Code language: Java (java)
private static List list() {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
List employees = session.createQuery("from Employee").list();
session.close();
return employees;
}
private static Employee read(Long id) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
Employee employee = (Employee) session.get(Employee.class, id);
session.close();
return employee;
}
Code language: Java (java)
private static Employee update(Employee employee) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.merge(employee);
session.getTransaction().commit();
session.close();
return employee;
}
Code language: Java (java)
private static void delete(Employee employee) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.delete(employee);
session.getTransaction().commit();
session.close();
}
Code language: Java (java)
We have created a file Main.java which will test all these functionality. Following is the complete source code of Main.java. File: /src/main/java/net/viralpatel/hibernate/Main.java package net.viralpatel.hibernate;
import java.sql.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class Main {
public static void main(String[] args) {
// Read
System.out.println("******* READ *******");
List employees = list();
System.out.println("Total Employees: " + employees.size());
// Write
System.out.println("******* WRITE *******");
Employee empl = new Employee("Jack", "Bauer", new Date(System.currentTimeMillis()), "911");
empl = save(empl);
empl = read(empl.getId());
System.out.printf("%d %s %s \n", empl.getId(), empl.getFirstname(), empl.getLastname());
// Update
System.out.println("******* UPDATE *******");
Employee empl2 = read(1l); // read employee with id 1
System.out.println("Name Before Update:" + empl2.getFirstname());
empl2.setFirstname("James");
update(empl2); // save the updated employee details
empl2 = read(1l); // read again employee with id 1
System.out.println("Name Aftere Update:" + empl2.getFirstname());
// Delete
System.out.println("******* DELETE *******");
delete(empl);
Employee empl3 = read(empl.getId());
System.out.println("Object:" + empl3);
}
private static List list() {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
List employees = session.createQuery("from Employee").list();
session.close();
return employees;
}
private static Employee read(Long id) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
Employee employee = (Employee) session.get(Employee.class, id);
session.close();
return employee;
}
private static Employee save(Employee employee) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Long id = (Long) session.save(employee);
employee.setId(id);
session.getTransaction().commit();
session.close();
return employee;
}
private static Employee update(Employee employee) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.merge(employee);
session.getTransaction().commit();
session.close();
return employee;
}
private static void delete(Employee employee) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.delete(employee);
session.getTransaction().commit();
session.close();
}
}
Code language: Java (java)
Code language: HTML, XML (xml)******* READ ******* Total Employees: 200 ******* WRITE ******* 201 Jack Bauer ******* UPDATE ******* Name Before Update:Paula Name Aftere Update:James ******* DELETE ******* Object:null
Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…
Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…
Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…
1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…
GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…
1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…
View Comments
I'm getting this error - any ideas why?
The import org.hibernate.Session cannot be resolved
Hi Tom, check if your maven dependencies are properly resolved. It seems that hibernate jar file is not resolved.
hi TOm,
I doing same u, but I cannot run project.
help me check it, thanks
error:
May 07, 2014 3:22:12 PM org.hibernate.cfg.Environment
INFO: Hibernate 3.2.3
May 07, 2014 3:22:12 PM org.hibernate.cfg.Environment
INFO: hibernate.properties not found
May 07, 2014 3:22:12 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
May 07, 2014 3:22:12 PM org.hibernate.cfg.Environment
INFO: using JDK 1.4 java.sql.Timestamp handling
May 07, 2014 3:22:12 PM org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
May 07, 2014 3:22:12 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml not found
at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1405)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1427)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1414)
at net.example.App.main(App.java:18)
Hi Viral
Seems I resolved the maven dependencies but im now getting the following errors:
- The method setFirstname(String) is undefined for the type Employee
- The method openSession() is undefined for the type SessionFactory
- The method setId(Long) is undefined for the type Employee
Hi Tom I also faced this problem. Just need to see hibernate.cfg.xml & Employee.hbm.xml file. it should be configured properly. I just correct this one & working fine
Can you post the amendments you made to get it working?
Hi Viral thanks for this tutorial. I got the output . I am not using Mavan. its just a simple read,Update, & delete Data from database.
Okay got this working now - Don't think I had the correct path set for the M2_REPO it should be ~/.M2 for linux but now i'm getting a Null Pointer exception on the delete function.
Total Employees: 1
******* WRITE *******
607 Jack Bauer
******* UPDATE *******
Exception in thread "main" java.lang.NullPointerException
at net.viralpatel.hibernate.Main.main(Main.java:33)
I think the reason you're getting this exception is that the auto-increment property for the SQL at the top of the tutorial is set as 606 (hence when the record is created, a value of 607 is assigned for the 'ID' as opposed to 1). Try re-creating the table with an auto-increment value of 0 for the 'create table' statement instead.
I am Getting below error:
: org.apache.maven.archetype.old.ArchetypeTemplateProcessingException: Una
t as it is not of packaging type 'pom'
Unable to add module to the current project as it is not of packaging type 'pom'
hello.......i prepared a simple java project using eclipse hibernate nd it was successfully run on eclipse but i want to see output on command form. using mysql database then which command i use ?????????????
Thanks for the amazing tutorial .. Absolutely amazing .. Everything is explained clearly.
This tutorial has a slight mistake.
Employee.hbm.xml is placed in package net.viralpate.hibernate which is wrong.
This Employee.hbm.xml must be placed in the src/main/resources folder.
Comments/Suggestions on the above posted by me........
Fantastic tutorials. Very straightforward and clear. Thanks so much!