Blank FROM clause in JPQL?

那年仲夏 提交于 2019-12-05 19:32:25
gpeche

I see several possible answers:

Within standard JPA there are two options, both involving Oracle DUAL "table"

  1. Map DUAL to an entity and use it in the FROM clause. It is the more "JPQL" way, but it is more involved:

In Java code:

@Entity(name = "Dual")
@Table(name = "SYS.DUAL")
public class Dual {
    @Id
    @Column(name = "DUMMY")
    private String dummy;
}

In orm.xml:

<named-query name="yourQuery">
    <query><![CDATA[
        SELECT FUNCTION('function_name', 'foo', 1234) FROM Dual d
    ]]>
    </query>
</named-query>

In client code:

Query q = entityManager.createNamedQuery("yourQuery");
  1. Just use a native query that uses DUAL

In orm.xml:

<named-native-query name="yourQuery">
    <query><![CDATA[
        SELECT function_name('foo', 1234) from sys.dual
    ]]>
    </query>
</named-native-query>

In client code:

Query q = entityManager.createNativeQuery("yourQuery");

As a last option, you can use some JPA implementation extension to JPA and avoid DUAL:

In short: I don't think it's possible to skip FROM clause of JPQL query.

JPQL grammar requires FROM clause to be present (see e.g. here or here).

Calling stored procedures/functions is typically done via native queries (see: createNativeQuery). So this should work:

em.createNativeQuery("select function_name('foo', 1234)").getSingleResult()

UPDATE (from comments):

That's true that JPA native queries don't support named parameters. So you must decide which is the lesser of two evils for you: either using JPQL with unnecessary entity reference or native query with positional parameters instead of named.

But be aware that FUNCTION is EclipseLink extension so it won't work should you decide to change a vendor.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!