HQL Insert Query



HQL supports only the INSERT INTO......... SELECT......... ; there is no chance to write INSERT INTO...........VALUES, i mean while writing the insert query, we need to select values from other table, we can’t insert our own values manually, you will understand by learning the following code.

Configuration configurationObj = new Configuration();
configurationObj.configure("hibernate.cfg.xml");
SessionFactory sessionFactoryObj = configurationObj.buildSessionFactory();
Session sessionObj = sessionFactoryObj.openSession();

Query queryObj = sessionObj.createQuery("INSERT INTO ITEMS_DATA (id,name,category)
SELECT E.id,E.name,E.category FROM ENTITIES_DATA E WHERE E.id=?");
queryObj.setParameter(0, 4);

int totalInserted = queryObj.executedUpdate();
if(totalInserted == 0){
    System.out.println(" No record inserted. ");
}else{
    System.out.println(" Total inserted records : "+totalInserted);
}

Transaction transactionObj = sessionObj.beginTransaction();
transactionObj.commit();
sessionObj.close();

sessionFactoryObj.close();