HQL insert Query hibernate

HQL insert Query hibernate

You can insert data to the table using HQL unfortunately it does not work as SQL where we could directly insert data using below sample SQL query:

INSERT INTO mother(First_Name, Last_Name, City, Zip, State) 
    VALUES('Wendy', 'Zuerlein', 'NY', '10038', 'NY')

Hibernate HQL support to insert data from another table using select statement please see java example below:

Note: This class is extension of previous tutorial. If you are interested to see full working example with all set up please refer this tutorial Hibernate One To Many Annotation Example

package com.javahonk;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.javahonk.util.HibernateUtil;

public class InsertQuery {
    static SessionFactory sf = HibernateUtil.getSessionFactory();

    public static void main(String[] args) {

        Session session = sf.openSession();

        System.out.println("Insert query example\n");

        Query query = session.createQuery("INSERT INTO Mother("
                + "firstName, lastName) "
                + "select c.firstName, c.lastName from Child as c");
        int noOfRowsInserted = query.executeUpdate();       

        System.out.println("Total no of rows inserted: "



HQL insert Query hibernate

For more information about HQL please read this hibernate official tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *