Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get returning ID in JPA after native query insert

I have the following code in JPA to return an auto generated ID after inserting using native query:

Query q = em.createNativeQuery("insert into .... returning ID", Long.class);
q.executeUpdate();

However, I'm getting the following error:

A result was returned when none was expected
like image 514
fareed Avatar asked Jul 17 '17 21:07

fareed


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 the difference between JPQL and native query?

Most of the time, a good JPQL Query can fulfill our needs and most importantly, maintain a level of abstraction from the actual database implementation. Using NativeQuery doesn't necessarily mean locking ourselves to one specific database vendor.

How execute native SQL query in JPA?

Select Query In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm.

What is native query in Hibernate?

You can use native SQL to express database queries if you want to utilize database-specific features such as query hints or the CONNECT keyword in Oracle. Hibernate 3. x allows you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations.


1 Answers

OK that was an easy one. I have just used q.getSingleResults() and it worked fine!

Query q = em.createNativeQuery(sql);
BigInteger biid = (BigInteger) q.getSingleResult();
long id = biid.longValue();
like image 139
fareed Avatar answered Sep 19 '22 15:09

fareed