Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting data in one table using HQL in Hibernate

I was reading the Hibernate HQL tutorial and found that HQL doesn't support INSERT INTO..VALUES.. but INSERT INTO..SELECT.. i.e. HQL only support insert from another table.

Suppose I want to insert same values in one table and that data is not from any other table i.e. the values are not in any other table.Then how can I do that in HQL?

Also, would like to know the rational behind such restrictions in HQL?

like image 999
Anand Avatar asked Oct 05 '12 11:10

Anand


People also ask

Which of the following is the correct method to insert object into the table in hibernate?

Using Session#persist() and Session#save() The Session interface provides many methods to perform CRUD operations on an Entity. Its persist() method will save the entity into the database. Session session = sessionFactory.

Can we use join in HQL query?

Some of the commonly supported clauses in HQL are: HQL From: HQL From is same as select clause in SQL, from Employee is same as select * from Employee . We can also create alias such as from Employee emp or from Employee as emp . HQL Join : HQL supports inner join, left outer join, right outer join and full join.

Can we use group by in HQL?

The HQL HAVING clause is used with GROUP BY clause.


2 Answers

You don't need to use hql to insert if the data is from another table.

Simply get a reference to your entity, get a hold of a Hibernate session, and call save().

According to http://docs.jboss.org/hibernate/orm/4.0/devguide/en-US/html/ch04.html#d0e2116

Pseudo-syntax for INSERT statements

INSERT INTO EntityName properties_list select_statement

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

like image 145
swemon Avatar answered Oct 22 '22 01:10

swemon


Hibernate is an ORM framework (Object-Relational Mapping).

Its job is that you give objects (Entities) to it and he manages the storage (through Session.save(), IIRC).

So, you do not use the HQL to insert new records, but use the ORM methods.

And (this is a guess) on the other hand, since loading entities from a table, copying them to other entities and storing them one by one is slow, HQL provides a shortcut to the SQL in the DB just for that specific operation for performance purposes.

like image 35
SJuan76 Avatar answered Oct 21 '22 23:10

SJuan76