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.
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.
public Query createNativeQuery(String sqlString,Class result-class); Creates a dynamic query using a native SQL statement that retrieves a single entity type.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With