Search code examples
javasqlhibernateormhql

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.


Solution

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

    int updateCount = session.createQuery("""
        insert into MyEntity(
            ...,
            max_column
        ) 
        select 
            ..., 
            max(id) 
        from SpecialEntity 
        """)
    .executeUpdate();