5

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?

knittl
  • 246,190
  • 53
  • 318
  • 364
J. Bend
  • 299
  • 2
  • 3
  • 14
  • Does the problem occur at em.createQuery(), or at q.getSingleResult()? Can you set appropriate logging level to see the generated SQL (Hibernate has this, not sure about EclipseLink)? – javashlook Aug 01 '09 at 12:24

4 Answers4

2

NVL() is supported now in newer versions of jpql

athspk
  • 6,722
  • 7
  • 37
  • 51
ash123
  • 197
  • 1
  • 3
  • 10
2

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
Xavi López
  • 27,550
  • 11
  • 97
  • 161
user2532187
  • 121
  • 1
  • 3
2

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

Robar
  • 1,929
  • 2
  • 30
  • 61
1

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.

ChssPly76
  • 99,456
  • 24
  • 206
  • 195