Native Sql Delete Query In Hibernate

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

Native Sql Delete Query In Hibernate

The current article lectures about the Native SQL Delete Query In Hibernate. We will learn this concept with an example.

We discussed the importance of Hibernate Native Query Example in the Hibernate in the previous lecture. So now we will learn to delete the objects using the same native sql query.

Hibernate Native Sql Delete Query

To implement the deletion, It is required to use the createNativeQuery() method which contains a native deletion query. Here is the example below.

Hibernate Native Sql Delete Query
Query query = session.createSQLQuery("delete from Book where book_id=43  ");

Hibernate Native Sql Delete Query Example

To implement the deletion using Native Sql Delete Query In Hibernate, We need to write the below code snippet.

Hibernate Native Sql Delete Query Example
            // delete book without param
            Query query = session.createSQLQuery("delete from Book where book_id=43  ");
            Integer count = query.executeUpdate();
            System.out.println("Number of records deleted: " + count);

Notice here we can not able to pass the dynamic values to make a query for all types of records.

Hibernate Native Sql Delete Query Example With Params

To pass the values as a parameter to make the query a dynamic query we can use given example.

Hibernate Native Sql Delete Query Example With Params
            // delete book with param
            query = session.createSQLQuery("delete from Book where book_id=?1");
            query.setParameter(1, 44);
            count = query.executeUpdate();
            System.out.println("Number of records deleted: " + count);

Refer to the GitHub repo Hibernate-Native-Query-Example-App for the entire example.

Leave A Reply