Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write HQL Insert query?

I am struggling to write a HQL query for inserting a new record in a table. I have seen some of insert query as below but I don't want insert data from another table as below code.

String hql = "INSERT INTO Employee(firstName, lastName, salary)"  + 
             "SELECT firstName, lastName, salary FROM old_employee";
Query query = session.createQuery(hql);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

For example I have a table "User" with three fields like name, age, number and I have entity for this user table. what will be the insert query for this?

like image 877
Ganesa Vijayakumar Avatar asked Sep 18 '15 13:09

Ganesa Vijayakumar


People also ask

Can we use join in HQL query?

HQL Join : HQL supports inner join, left outer join, right outer join and full join. For example, select e.name, a. city from Employee e INNER JOIN e.

Which is better SQL or HQL?

The following are some of the reasons why HQL is preferred over SQL: Provides full support for relational operations. It is possible to represent SQL Queries in the form of objects in HQL which uses classes and properties instead of tables and columns. Return results as objects.

What is HQL write difference between HQL and SQL?

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries, which in turns perform action on database.


2 Answers

In HQL, only the INSERT INTO … SELECT … is supported; there is no INSERT INTO … VALUES. HQL only support insert from another table.

So query INSERT from SELECT is possible like this

Query query = session.createQuery("insert into Stock(stock_code, stock_name)" +
                "select stock_code, stock_name from backup_stock");
int result = query.executeUpdate();

Got from here secion 4

If you have values and Entity just call

MyEntity e=new MyEntity();
e.setXXXX(the XXX values);
save(e);
like image 140
StanislavL Avatar answered Sep 30 '22 21:09

StanislavL


HQL doesn't support such INSERTs so you have to do this by creating and persisting new entity.

You can read about it here.

Only the INSERT INTO ... SELECT ... form is supported. You cannot specify explicit values to insert.

like image 35
Elon Than Avatar answered Sep 30 '22 21:09

Elon Than