Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select nvl(max(c.EmployeeId),0) in JPQL?

I'm using oracle10g database and eclipselink, I need to obtain the last inserted key from the table so i've created this query

javax.persistence.Query q =   
                    em.createQuery("SELECT nvl(MAX(c.myAtt),0) " +   
                        "from myTable as c");   
             return Integer.parseInt(q.getSingleResult().toString());   `

But when the table is empy(sometimes it might get empty) i'm getting ILEGAL ARGUMENT EXCEPTION, cause: JPQL Exception, detail: "An exception occurred while creating a query in EntityManager". What i'm doing wrong?

like image 392
J. Bend Avatar asked Aug 01 '09 00:08

J. Bend


People also ask

What is the difference between JPQL and SQL?

SQL works directly against relational database tables, records and fields, whereas JPQL works with Java classes and instances. For example, a JPQL query can retrieve an entity object rather than field result set from database, as with SQL.

Which method is used to execute a select JPQL query?

The EntityManager's createQuery is used to create the Query instance whose getResultList method is then used to execute the JPQL query passed to createQuery as the parameter.

Which is faster JPQL or native query?

Also, JPA criteria queries are as fast as JPQL queries, and JPA native queries have the same efficiency as JPQL queries. This test run has 11008 records in the Order table, 22008 records in the LineItem table, and 44000 records in the Customer table.


4 Answers

In the meanwhile somebody else could have inserted something in Autorizaciones and then you receive the wrong id

like image 149
Robar Avatar answered Sep 29 '22 02:09

Robar


NVL() is supported now in newer versions of jpql

like image 45
ash123 Avatar answered Sep 29 '22 00:09

ash123


You could use the COALESCE function. It can be used to achieve the same as nvl. For instance:

select nvl(columna,'1') from table
select COALESCE(columna,'1') from table
like image 24
user2532187 Avatar answered Sep 29 '22 01:09

user2532187


Paraphrasing Apu, "I don't know what part of that question to correct first" :-)

First of all, retrieving last inserted key in this way is a VERY BAD THING © It's dangerous, inefficient and most of all, unnecessary as your JPA already does it for you: once you insert your entity, its identifier property will automatically be updated to contain its primary key.

Secondly, as far as your query goes, "myTable" is not something you would use in JPQL, you need to specify your entity name instead (e.g. if you're mapping "Car" to "CAR_TABLE" you should use "Car" instead of "CAR_TABLE" in JPQL queries).

Finally, NVL() is not supported by JPQL. It is supported (sort of, via Expression.ifNull()) by EclipseLink Expressions. Not that you'd need it in a scenario like this, anyway.

like image 20
ChssPly76 Avatar answered Sep 29 '22 01:09

ChssPly76