This blog will be helpful to create simple java application using hibernate:
To make things very easy we will be taking an example of student. In this example we will be creating a "StudentRecord" table and will insert dummy student data in it.
We will see how "Hibernate" can create a table for us. Hence we don't need to worry about creating a table manually. Our application will take care of not just insertion
of the student record but creating of table as well.
There are few simple steps we need to perform for writing simple hibernate java application.
Here are the main steps:
1. Create Entity Class
2. Create ".hbm" file for the student
3. Hibernate configuration XML file
4. Create a Dummy Class to test application
5. Run and Verify
6. Trouble Shoot
Let's see the steps in detailed
1. Create Entity Class
This is a POJO class which holds all the properties related to student along with the setter and getter methods.
Here is the quick code snippet:
package student.persistence;
public class Student {
private int studentId;
private String studentName;
private String email;
private String gender;
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
In our case we have used four properties "studentId", "studentName", "email", "gender". Whose value we will be storing inside the table in the proceeding steps:
2. Create ".hbm" file for the student
For every "POJO" we need to create ".hbm" file. ".hbm" file contains the mapping of "POJO" (Class) with "Relational Table" (StudentRecord) in our case.
At the same time ".hbm" file contains the association between "attributes" of the "POJO" with the "column" of the "Table".
We can also specify the constraint like "primary key" , "composite key" etc in ".hbm" file.
Here is the quick code snippet:
<?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>
<class name="student.persistence.Student" table="StudentRecord">
<id name="studentId">
<generator class="assigned"></generator>
</id>
<property name="studentName"></property>
<property name="email"></property>
<property name="gender"></property>
</class>
</hibernate-mapping>
3. Hibernate configuration XML file (.cfg) file
For every application there is one "hibernate.cfg.xml" file. Which is the main mapping file. It contains the details related to database, connection,username,
password,dialect etc. Along with the few hibernate specific properties can also be specified.
Here is the quick reference of "hibernate.cfg.xml" file:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/student</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="student.hbm.xml" />
</session-factory>
</hibernate-configuration>
In our application we have used the "MySQLDialect" which means our application will be creating a table inside "MySql" database.
Property "hibernate.connection.url" contains the details like under which databse/schema our tables should get created. In Url "..../student" we have specified
that means that our table "StudentRecord" will be created under "student" schema.
Property "<mapping resource="student.hbm.xml" />", loads the student.hbm.xml file.
Property "<property name="show_sql">true</property>" will print the all the sql which our application will fire. (Its very helpful for the debugging purpose)
4. Create a Dummy Class to test application
In our java application we will be using "StudentDemo" as an entry point for the application. In our dummy class we will be doing following operations
Load Configuration file ("hibernate.cfg.xml")
Build Session Factory
Open Session
Create, Instantiate, Initialize a student pojo
begin the transaction
save/persist student pojo
commit the transaction
Close Session and Factory respectively.
Here is the code snippet for quick reference:
package student.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import student.persistence.Student;
public class StudentDemo {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Student student = new Student();
student.setStudentName("Peter");
student.setGender("M");
student.setEmail("peter@test.com");
Transaction tx = session.beginTransaction();
session.save(student);
System.out.println("Student Record Saved Successfully! ");
tx.commit();
session.close();
factory.close();
}
}
5. Run and Verify
When we run the "StudentDemo" class we can see below console output:
Jul 30, 2015 2:55:35 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.0.CR2}
Jul 30, 2015 2:55:35 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jul 30, 2015 2:55:35 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jul 30, 2015 2:55:37 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.0.Final}
Jul 30, 2015 2:55:37 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Refer to Hibernate 3.6 Migration Guide!
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/student]
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jul 30, 2015 2:55:40 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Jul 30, 2015 2:55:42 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate:
drop table if exists StudentRecord
Hibernate:
create table StudentRecord (
studentId integer not null,
studentName varchar(255),
email varchar(255),
gender varchar(255),
primary key (studentId)
)
Jul 30, 2015 2:55:43 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Student Record Saved Successfully!
Hibernate:
insert
into
StudentRecord
(studentName, email, gender, studentId)
values
(?, ?, ?, ?)
Jul 30, 2015 2:55:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost:3306/student]
We can see that first of all hibernate goes to drop the table if the table already exist. Then it creates the table using auto generated "Create" script.
and then it insert the record into the "StudentRecord" table.
Here is the snippet we can see in the database:
6. Trouble Shoot
Overall our application package structure should look like this:
For more trouble shoot please refere "http://technoknowledgespread.blogspot.in/2015/07/common-errors-while-configuring.html"
Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics
To make things very easy we will be taking an example of student. In this example we will be creating a "StudentRecord" table and will insert dummy student data in it.
We will see how "Hibernate" can create a table for us. Hence we don't need to worry about creating a table manually. Our application will take care of not just insertion
of the student record but creating of table as well.
There are few simple steps we need to perform for writing simple hibernate java application.
Here are the main steps:
1. Create Entity Class
2. Create ".hbm" file for the student
3. Hibernate configuration XML file
4. Create a Dummy Class to test application
5. Run and Verify
6. Trouble Shoot
Let's see the steps in detailed
1. Create Entity Class
This is a POJO class which holds all the properties related to student along with the setter and getter methods.
Here is the quick code snippet:
package student.persistence;
public class Student {
private int studentId;
private String studentName;
private String email;
private String gender;
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
In our case we have used four properties "studentId", "studentName", "email", "gender". Whose value we will be storing inside the table in the proceeding steps:
2. Create ".hbm" file for the student
For every "POJO" we need to create ".hbm" file. ".hbm" file contains the mapping of "POJO" (Class) with "Relational Table" (StudentRecord) in our case.
At the same time ".hbm" file contains the association between "attributes" of the "POJO" with the "column" of the "Table".
We can also specify the constraint like "primary key" , "composite key" etc in ".hbm" file.
Here is the quick code snippet:
<?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>
<class name="student.persistence.Student" table="StudentRecord">
<id name="studentId">
<generator class="assigned"></generator>
</id>
<property name="studentName"></property>
<property name="email"></property>
<property name="gender"></property>
</class>
</hibernate-mapping>
3. Hibernate configuration XML file (.cfg) file
For every application there is one "hibernate.cfg.xml" file. Which is the main mapping file. It contains the details related to database, connection,username,
password,dialect etc. Along with the few hibernate specific properties can also be specified.
Here is the quick reference of "hibernate.cfg.xml" file:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/student</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="student.hbm.xml" />
</session-factory>
</hibernate-configuration>
In our application we have used the "MySQLDialect" which means our application will be creating a table inside "MySql" database.
Property "hibernate.connection.url" contains the details like under which databse/schema our tables should get created. In Url "..../student" we have specified
that means that our table "StudentRecord" will be created under "student" schema.
Property "<mapping resource="student.hbm.xml" />", loads the student.hbm.xml file.
Property "<property name="show_sql">true</property>" will print the all the sql which our application will fire. (Its very helpful for the debugging purpose)
4. Create a Dummy Class to test application
In our java application we will be using "StudentDemo" as an entry point for the application. In our dummy class we will be doing following operations
Load Configuration file ("hibernate.cfg.xml")
Build Session Factory
Open Session
Create, Instantiate, Initialize a student pojo
begin the transaction
save/persist student pojo
commit the transaction
Close Session and Factory respectively.
Here is the code snippet for quick reference:
package student.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import student.persistence.Student;
public class StudentDemo {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Student student = new Student();
student.setStudentName("Peter");
student.setGender("M");
student.setEmail("peter@test.com");
Transaction tx = session.beginTransaction();
session.save(student);
System.out.println("Student Record Saved Successfully! ");
tx.commit();
session.close();
factory.close();
}
}
5. Run and Verify
When we run the "StudentDemo" class we can see below console output:
Jul 30, 2015 2:55:35 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.0.CR2}
Jul 30, 2015 2:55:35 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jul 30, 2015 2:55:35 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jul 30, 2015 2:55:37 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.0.Final}
Jul 30, 2015 2:55:37 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Refer to Hibernate 3.6 Migration Guide!
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/student]
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jul 30, 2015 2:55:40 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Jul 30, 2015 2:55:42 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate:
drop table if exists StudentRecord
Hibernate:
create table StudentRecord (
studentId integer not null,
studentName varchar(255),
email varchar(255),
gender varchar(255),
primary key (studentId)
)
Jul 30, 2015 2:55:43 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Student Record Saved Successfully!
Hibernate:
insert
into
StudentRecord
(studentName, email, gender, studentId)
values
(?, ?, ?, ?)
Jul 30, 2015 2:55:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost:3306/student]
We can see that first of all hibernate goes to drop the table if the table already exist. Then it creates the table using auto generated "Create" script.
and then it insert the record into the "StudentRecord" table.
Here is the snippet we can see in the database:
6. Trouble Shoot
Overall our application package structure should look like this:
For more trouble shoot please refere "http://technoknowledgespread.blogspot.in/2015/07/common-errors-while-configuring.html"
Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics






