Hibernate Insert

This tutorial will help you to learn how to insert data into table by using hibernate.

Hibernate Insert

Hibernate Insert

This tutorial will help you to learn how to insert data into table by using hibernate.

Hibernate insert example : Hibernate provides 3 ways to insert data into database table.

1. By using native SQL

2.By using Hibernate Query language(HQL).

3.By using hibernate criteria.

In this section we are giving an insertion example by using native SQL.

Native SQL:  Hibernate provides native SQL to express database queries. Then pass a string containing the sql query to the method createSQLQuery().

Example -In this example student is our table in which we are inserting roll_no , name and course.

We used here native SQL as - String sql = "INSERT INTO student(roll_no, name,course) VALUES(12, 'Roxi' ,'Hibernate')";

createSQLQuery() method is used to call our native SQL statement directly by using session.

Here is your code -

package net.roseindia.main;

import net.roseindia.util.HibernateUtil;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class MainClazz {

public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {

transaction = session.beginTransaction();
String sql = "INSERT INTO student(roll_no, name,course) VALUES(12, 'Roxi' ,'Hibernate')";
Query query = session.createSQLQuery(sql);
query.executeUpdate();
session.getTransaction().commit();

session.flush();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}

Output:

Hibernate: insert into student(roll_no, name,course) values(12, 'Roxi' ,'Hibernate')
New record inserted

Click here to download complete source code