Hibernate Native Sql Update Query Example

By | | Updated : 2022-02-19 | Viewed : 114 times

Hibernate Native Sql Update Query Example

The article talks about the Hibernate Native SQL Update Query with examples.

Hibernate Native Sql Update Query

To implement the update, we need to use the createSQLQuery() method in Session class. Notice below the example for native SQL update with hibernate.

Hibernate Native Sql Update Query
Query query = session.createSQLQuery("update Book b set b.book_name = 'testBook' where b.book_id=32");

Hibernate Native Sql Update Query Example

we will now look at a proper example to update with Hibernate native sql.

Hibernate Native Sql Update Query Example
            // update the book
            Query query = session.createSQLQuery("update Book b set b.book_name = 'testBook' where b.book_id=32");
            Integer count = query.executeUpdate();
            System.out.println("Number of records updated: " + count);

Hibernate Native Sql Update Query Example With Params

Here it is not possible to pass dynamic values to the columns. So we need to use passing parameters.

Hibernate Native Sql Update Query Example With Params
// update the book
            query = session.createSQLQuery("update Book b set b.book_name = \'testBook\' where b.book_id=?1");
            query.setParameter(1, 33);
            count = query.executeUpdate();
            System.out.println("Number of records updated: " + count);

For the entire GitHub repo, Please refer Hibernate-Native-Query-Example-App

Leave A Reply