HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

Hibernate Insert Query Tutorial

By Lokesh Gupta | Filed Under: Hibernate

Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database. This means you are not required to build and execute SQL queries for interaction with database. You just have to instruct hibernate for that by calling hibernate APIs and hibernate will create and execute those SQL queries on behalf of you.

In this hibernate tutorial, I am giving example of inserting data in a single table. We have an object in application i.e. Employee. We want to store it in database. Employee class has following attributes:

  • employee id – Integer
  • email – String
  • first name – String
  • last name – String

It can have more fields, but I am taking only four to make example concrete.

1. Hibernate entity class

Hibernate talks with Java POJO classes which are marked as hibernate entities. To convert a Java class into entity, we need to apply @Entity annotation on it. There are other hibernate annotations like @Table, @Column and @Id etc which help in mapping entity fields to database table and columns.

Employee entity class looks like below after applying the annotations.

@Entity
@Table(name = "EMPLOYEE", uniqueConstraints = {
		@UniqueConstraint(columnNames = "ID"),
		@UniqueConstraint(columnNames = "EMAIL") })
public class EmployeeEntity implements Serializable 
{	
	private static final long serialVersionUID = -1798070786993154676L;
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "ID", unique = true, nullable = false)
	private Integer id;
	
	@Column(name = "EMAIL", unique = true, nullable = false, length = 100)
	private String email;
	
	@Column(name = "FIRST_NAME", unique = false, nullable = false, length = 100)
	private String firstName;
	
	@Column(name = "LAST_NAME", unique = false, nullable = false, length = 100)
	private String lastName;

	//Getters and setters
}

2. Hibernate configuration

Next step is to configure hibernate in “hibernate.cgf.xml” file. This file contains all available entities in system and database connection meta-data.

<?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">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedemo</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
		<property name="hbm2ddl.auto">create</property>
        <mapping class="hibernate.test.dto.EmployeeEntity"></mapping>
    </session-factory>
</hibernate-configuration>

3. Hibernate SessionFactory

Now hibernate configuration is on place, we have to build the hibernate session factory. Session factory is used to obtain the connection of database and various activities like commit and rollback.

public class HibernateUtil 
{
	private static final SessionFactory sessionFactory = buildSessionFactory();
	 
    private static SessionFactory buildSessionFactory() 
    {
        try 
        {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure(new File("hibernate.cgf.xml")).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;
    }
 
    public static void shutdown() {
    	// Close caches and connection pools
    	getSessionFactory().close();
    }
}

4. Hibernate insert query example

Finally we will use this hibernate session factory to execute insert query to save employee in database.

public class TestHibernateInsert {
	
	public static void main(String[] args) 
	{
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
       
		//Add new Employee object
		EmployeeEntity emp = new EmployeeEntity();
		emp.setEmail("lokesh@mail.com");
		emp.setFirstName("lokesh");
		emp.setLastName("gupta");
		
		//Save the employee in database
		session.save(emp);

		//Commit the transaction
		session.getTransaction().commit();
		HibernateUtil.shutdown();
	}
}

Program logs.

Hibernate: insert into EMPLOYEE (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)

Lets verify the data in database.

Hibernate insert query example
Hibernate insert query example

5. Troubleshooting

  1. Please ensure to add hibernate and mysql driver dependencies in project. In maven these are as below:
    <dependency>
    	<groupId>org.hibernate</groupId>
    	<artifactId>hibernate-commons-annotations</artifactId>
    	<version>3.0.0.ga</version>
    </dependency>
    <dependency>
    	<groupId>org.hibernate</groupId>
    	<artifactId>hibernate-annotations</artifactId>
    	<version>3.3.0.ga</version>
    </dependency>
    <dependency>
    	<groupId>mysql</groupId>
    	<artifactId>mysql-connector-java</artifactId>
    	<version>5.1.6</version>
    </dependency>
    
  2. Verify that hibernate.cgf.xml file is present and has valid database meta-data.
Download Source Code

Happy Learning !!

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

7
Leave a Reply

This comment form is under antispam protection
5 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
6 Comment authors
This comment form is under antispam protection
  Subscribe  
newest oldest most voted
Notify of
aman

Hi Lokesh,
is it possible using entityManager?

Vote Up0Vote Down  Reply
8 months ago
ravi

Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
Exception in thread “main” java.lang.ExceptionInInitializerError
at hibernateutil.HibernateUtil.buildSessionFactory(HibernateUtil.java:22)
at hibernateutil.HibernateUtil.(HibernateUtil.java:10)
at hibernatetesinsert.TestHibernateInsert.main(TestHibernateInsert.java:12)
Caused by: java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.hibernate.cfg.Configuration.(Configuration.java:120)
at hibernateutil.HibernateUtil.buildSessionFactory(HibernateUtil.java:17)
… 2 more
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
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)
… 4 more

Vote Up0Vote Down  Reply
2 years ago
ravi

i am getting above error

Vote Up0Vote Down  Reply
2 years ago
Lokesh Gupta

Add apache commons logging (link) to classpath.

Vote Up0Vote Down  Reply
2 years ago
Akhildas

how to connect front end to hibernate

Vote Up0Vote Down  Reply
4 years ago
bhaskar

Hi ,

Can you tell how to write inner join in criteria.

Vote Up0Vote Down  Reply
5 years ago
nitesh

Sir this is not Hibernate insert query example here u are just inserting data using setter method of modal class .
hibernate insert query is different.

Vote Up0Vote Down  Reply
6 years ago

Search Tutorials

Hibernate Tutorial

  • Hibernate – Introduction
  • Hibernate – Hello World
  • Hibernate – Get/Fetch
  • Hibernate – Persist
  • Hibernate – Merge & Refresh
  • Hibernate – Get Entity Reference
  • Hibernate – BLOB
  • Hibernate – Save Update
  • Hibernate – Persistence LifeCycle
  • Hibernate – SessionFactory
  • Hibernate – Entities Equality
  • Hibernate – Cascade Types
  • Hibernate – Lazy Loading
  • Hibernate – Criteria Queries
  • Hibernate – HQL
  • Hibernate – Named Query
  • Hibernate – Mappings
  • Hibernate – First Level Cache
  • Hibernate – Second Level Cache
  • Hibernate – EhCache Configuration
  • Hibernate – OSCache Configuration
  • Hibernate – C3P0 Connection Pool
  • Hibernate – In memory Database
  • Hibernate – Bean Validation
  • Hibernate – Validator CDI
  • UnexpectedTypeException

Hibernate Annotations

  • Hibernate – JPA 2 Annotations
  • Annotations Vs Mappings
  • Hibernate – @Immutable
  • Hibernate – @NaturalId
  • Hibernate – @OneToMany
  • Hibernate – @ManyToMany
  • Hibernate – @OneToOne

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Python Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz