Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to INSERT using a SELECT in Hibernate

I need to implement the following request in hibernate:

insert into my_table(....,max_column)
values(...,(select max(id) from special_table where ....))

How to do that in hibernate, using annotations? special_table may be not a child or dependency of my_table, just a subselect.

like image 318
avalon Avatar asked Jun 04 '15 05:06

avalon


People also ask

How to write insert Query using Hibernate?

Hibernate Query Language (HQL) supports two kinds of insert statement: insert … ​ values , where the attribute values to insert are given directly as tuples. This inserts a single row in the database, or multiple rows if we provide multiple tuples in the values clause.

How to insert data in Hibernate using HQL?

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.

Which type of query helps in select insert update and delete data from the database in hibernate?

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.

How do you update an object in hibernate?

We can update an object in hibernate by calling the update() method, provided by the org. hibernate. Session. Though the update() method is used to update an object, there are two different ways to use update() method.


1 Answers

You can use the INSERT INTO ... SELECT ... feature:

int updateCount = session.createQuery("""
    insert into MyEntity(
        ...,
        max_column
    ) 
    select 
        ..., 
        max(id) 
    from SpecialEntity 
    """)
.executeUpdate();
like image 137
Vlad Mihalcea Avatar answered Oct 13 '22 14:10

Vlad Mihalcea