java 在 JPQL 中选择 nvl(max(c.EmployeeId),0)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1215495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:40:14  来源:igfitidea点击:

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

javapersistencejpqlejbql

提问by J. Bend

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

我正在使用 oracle10g 数据库和 eclipselink,我需要从表中获取最后插入的键,所以我创建了这个查询

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?

但是当表是空的(有时它可能会变空)时,我得到了 ILEGAL ARGUMENT EXCEPTION,原因:JPQL 异常,详细信息:“在 EntityManager 中创建查询时发生异常”。我在做什么错?

回答by Robar

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

与此同时,其他人可能在 Autorizaciones 中插入了一些东西,然后你会收到错误的 id

回答by ash123

NVL()is supported now in newer versions of jpql

NVL()较新版本的 jpql 现在支持

回答by user2532187

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

您可以使用该COALESCE功能。它可以用来实现与nvl. 例如:

select nvl(columna,'1') from table
select COALESCE(columna,'1') from table

回答by ChssPly76

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

释义Apu,“我不知道该问题的哪一部分首先要纠正”:-)

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.

首先,以这种方式检索最后插入的键是一件非常糟糕的事情©它很危险,效率低下,最重要的是,没有必要,因为您的 JPA 已经为您做了:一旦您插入您的实体,它的标识符属性将自动更新为包含其主键。

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).

其次,就您的查询而言,“myTable”不是您将在 JPQL 中使用的东西,您需要指定您的实体名称(例如,如果您将“Car”映射到“CAR_TABLE”,则应使用“Car”代替JPQL 查询中的“CAR_TABLE”)。

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.

最后,NVL()JPQL 不支持。它Expression.ifNull()EclipseLink Expressions支持(有点,通过)。无论如何,并不是在这样的场景中你需要它。