Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update query in createNativeQuery

I want to run an Update query using createNativeQuery in entityManager. I am not able to run it.

My class structure :

class ABC_DAO
{

List<a> = entityManager.createNativeQuery(select.......); //sql1 : it is working fine

Sysout("some value"); // it is working


entityManager.createNativeQuery(update.......);// ***sql2 :it is not working***

Sysout("some value"); // it is working

}

Hibernate is not executing sql2 but executing sql2. We are using Postgres db. This query has to be in Sql. We are using Hibernate with JPA.

like image 352
Abhi Avatar asked Feb 02 '18 02:02

Abhi


People also ask

What is createNativeQuery in JPA?

Create ad-hoc native queries Creating an ad-hoc native query is quite simple. The EntityManager interface provides the createNativeQuery method for it. It returns an implementation of the Query interface, which is the same that you get when you call the createQuery method to create a JPQL query.

What is query createNativeQuery string sqlString?

public Query createNativeQuery(String sqlString,Class result-class); Creates a dynamic query using a native SQL statement that retrieves a single entity type.

What is native query in SQL?

Native query refers to actual sql queries (referring to actual database objects). These queries are the sql statements which can be directly executed in database using a database client.

Why do we use native query?

You may also express queries in the native SQL dialect of your database. This is useful if you want to utilize database specific features such as query hints or the CONNECT BY option in Oracle. It also provides a clean migration path from a direct SQL/JDBC based application to Hibernate.


1 Answers

Let my try to help you on behalf of your erroneous code example and problem description.

1) You will only get a List as result of a query if you call getResultList() on it, otherwise sql1 would not work (Please post the complete code, if you want to get help):

List<a> = entityManager.createNativeQuery("sql1", a.class).getResultList();

2) For update statements you have to call the method executeUpdate() and not getResultList() (or getSingleResult())to send the native SQL statement to the database:

int countUpdated = entityManager.createNativeQuery("sql2").executeUpdate();
like image 120
Georg Leber Avatar answered Oct 06 '22 04:10

Georg Leber