hibernate

Hibernate Insert Example

In this example, we will show how to use hibernate to insert data into database. Hibernate is one of the few JPA (Java Persistence API) provider. Hibernate is extensively used for persistence layer of building a enterprise application. We will configure our hibernate with hibernate.cfg.xml and then we will create an example mapping with example.hbm.xml. We will show how a simple program will persist data in database.

1. Introduction

Hibernate is an object-relational mapping (ORM) framework for java language. It provides a way to map Java objects to relational database tables. We can achieve this mapping through XML mapping or annotation mapping. In this example we will be showing mapping through XML mapping. We will use a simple database table of STUDENT to insert a student record through a java program which will persist data in database.

2. Environment

  1. Windows 7
  2. Java version 7
  3. Eclipse Kepler 4.3
  4. Maven 3.0.4
  5. MySQL 5.0.86
  6. JBoss-Hibernate Plugin 4.1.2

3. Example Outline

We will create a maven project and add the required dependencies that will help us build a hibernate persistence entity object. We will be using mapping rather than annotation in this example. We will create a database and database table in MySQL database. We will write a simple java program to persist data for our entity class into the database.

4. Example

Following is the step by step guide to use hibernate for insert operation.

4.1 Create a Maven Project

Create a new maven project in eclipse. Fill in the details for GroupId as com.javacodegeeks.example and ArtifactId as HibernateInsertExample as shown below.

Maven Project
Maven Project

4.2 Add Hibernate dependencies

Let’s add hibernate dependencies in maven pom.xml, so we can use Hibernate provided APIs to write our entity class and test program.

pom.xml

<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javacodegeeks.example</groupId>
	<artifactId>HibernateInsertExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.11.Final</version>
		</dependency>
	</dependencies>
</project>

4.3 Create Hibernate Configuration File

We will use a hibernate configuration file hibernate.cfg.xml under resources folder of our maven project. This is shown in the below screenshot:

Hibernate Configuration File
Hibernate Configuration File

Do not forget to check “Create a console configuration” checkbox as shown above. This will open hibernate console configuration in next screen. Once you click “Finish”, you will be able to see database and all the tables of that database. Now the file hibernate.cfg.xml will look like below:

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/hbtutorial</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    </session-factory>
</hibernate-configuration>

4.4 Create Java Object

Since we are showing an insert operation, we will create a simple entity class Student . We will create a java object Student.java as shown below:

Student.java

package com.javacodegeeks.example;

import java.util.Date;


public class Student 
{
	private int sid;
	private String student_name;
	private double student_marks;
	private Date studentjoin_date;
	
	public Student()
	{
		
	}
	
	public int getSid() {
		return sid;
	}
	public void setSid(int sid) {
		this.sid = sid;
	}
	public String getStudent_name() {
		return student_name;
	}
	public void setStudent_name(String student_name) {
		this.student_name = student_name;
	}
	public double getStudent_marks() {
		return student_marks;
	}
	public void setStudent_marks(double student_marks) {
		this.student_marks = student_marks;
	}
	public Date getStudentjoin_date() {
		return studentjoin_date;
	}
	public void setStudentjoin_date(Date studentjoin_date) {
		this.studentjoin_date = studentjoin_date;
	}		
}

On corresponding level, we will create a database table student in our mysql database hbtutorial . as shown below


CREATE TABLE student (sid INT, studentname VARCHAR(255), studentmarks DOUBLE, studentjoindate DATE, CONSTRAINT sid PRIMARY KEY(sid));

4.5 Map Java Object to Database

Now we will create a mapping file to map our Student java object to student database table. In eclipse, under resources folder of our project, create a file with option Hibernate XML mapping file (hbm.xml). We will have Student.hbm.xml

Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Nov 12, 2016 12:24:29 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.javacodegeeks.example.Student" table="STUDENT">
        <id name="sid" type="int">
            <column name="SID" />
            <generator class="assigned" />
        </id>
        <property name="student_name" type="java.lang.String">
            <column name="STUDENTNAME" />
        </property>
        <property name="student_marks" type="double">
            <column name="STUDENTMARKS" />
        </property>
        <property name="studentjoin_date" type="java.util.Date">
            <column name="STUDENTJOINDATE" />
        </property>
    </class>
</hibernate-mapping>

4.6 Hibernate Test Program for insert operation

We will create a test program in eclipse under src -> main -> java folder with name HibernateInsertProgram .

HibernateInsertProgram.java

package com.javacodegeeks.example;

import java.util.Date;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateInsertProgram {
	private static SessionFactory factory;
	private static ServiceRegistry serviceRegistry;

	@SuppressWarnings("deprecation")
	public static void main(String[] args) 
	{
		addAllConfigs();
		
		HibernateInsertProgram hi = new HibernateInsertProgram();
		long one = hi.insertStudent(1," Mark Johnson", 58, new Date("08/11/2008"));
		long two = hi.insertStudent(2, "Jill Rhodes", 95, new Date("08/08/2008"));
		
		System.out.println(" We successfully inserted students in student table...they are..." + one + " and " + two);
	}
	
	public static void addAllConfigs()
	{
		Configuration config = new Configuration();
		config.configure();
		config.addAnnotatedClass(Student.class);
		config.addResource("Student.hbm.xml");
		serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
		factory = config.buildSessionFactory(serviceRegistry);
	}

	private long insertStudent(int id, String name, int marks, Date joindate)
	{
		Session session = factory.openSession();
		Transaction tx = null;
		Integer stId = null;
		try
		{
			tx = session.beginTransaction();
			Student st = new Student();
			st.setSid(id);
			st.setStudent_name(name);
			st.setStudent_marks(marks);
			st.setStudentjoin_date(joindate);
			
			stId = (Integer) session.save(st);
			tx.commit();
		} 
		catch (HibernateException ex)
		{
			if(tx != null)
				tx.rollback();
		}
		finally
		{
			session.close();
		}
		
		return stId;
	}
}

Once you run this program in your eclipse, it will insert the two student records in Student database table.

5. Conclusion

In this example, we showed how a simple program can be used for insert operation with hibernate. We did this with the help of relational mapping feature of Hibernate Persistence Framework.

6. Download The Source Code

You can download the source code of this example here.

Download
You can download the full source code of this example here: hibernateinsertexample 

Yogesh Mali

Yogesh currently lives in Minneapolis and works as a Senior Software Engineer. He has a masters degree in Computer Science from University of Minnesota, Twin Cities. At graduate school, he did research in programming languages because of his love for functional and object oriented programming. Currently he delves into more details of Java, web development and security. Previously he worked as a product manager to create web application for health insurance brokers. In his free time, he listens to music and writes fictional stories.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button