别名预期长度为0; hibernate查询缓存的实际长度为1

时间:2014-09-11 13:48:21

标签: java hibernate jpa

String q1Str = "SELECT parent_id FROM meta WHERE st_id = "+childIds+";";
Query q1 = em.createNativeQuery(q1Str);
//q1.setHint("org.hibernate.cacheable", true);
Object parentId = null;
try{
parentId = q1.getSingleResult();
}catch(NoResultException nre){
    //nope
}

启用hibernate.cacheable会引发以下异常

  

别名预期长度为0;实际长度为1

2 个答案:

答案 0 :(得分:0)

我认为当查询的表没有主键时会发生这种情况。

答案 1 :(得分:0)

所以,这也发生在我身上,在搜索/研究了可能的解决方案之后, 决定放弃,但是经过很长的调试会话(不是Session.class)之后,我偶然发现了 解决方案。

等等...环境

休眠核心5.3.0。最终版

Wildfly 20.0.1最终版

Java 11

PostgreSQL 9.4吗? (不知道确切的版本,对不起)

Infinispan进行缓存

所以,首先使用

em.createNamedQuery("MyClass.findMyStuff", Tuple.class)
            .setParameter(0, declarationDate)
            .setHint("org.hibernate.cacheable", true)
            .getResultList()

我收到与此类似的错误

别名的预期长度为0;实际长度是1

但是,当然,它们具有不同的数字(而不是0和1)

注意:我的本机sql就是这样

从mytable中选择a.date作为mydate,将a.id作为myid,将a.test作为mytest,其中date =?0

所以,有什么臭气的风扇...

尝试过

em.createNamedQuery("MyClass.findMyStuff", Tuple.class)
            .setParameter(0, declarationDate)
            .setHint("org.hibernate.cacheable", true)
            .unwrap(NativeQuery.class)
            .addSynchronizedQuerySpace("myQuery_space")
            .getResultList()

,但我失败了……尝试了所有可用的addSynchronized方法中的相同内容 NativeQuery.class,但是每次休眠都告诉我去娱乐一下。

然后,我尝试使用HQL重写查询,但是祝您好运...重写所有这些 子选择,联接,HQL中没有的只是一厢情愿的想法-不可行(在我 案件。请注意,我的资源有限)。

回到我的起点...并更改此

em.createNamedQuery("MyClass.findMyStuff", Tuple.class)
            .setParameter(0, declarationDate)
            .setHint("org.hibernate.cacheable", true)
            .unwrap(NativeQuery.class)
            .addSynchronizedQuerySpace("myQuery_space")
            .getResultList()

em.createNamedQuery("MyClass.findMyStuff", Tuple.class)
            .setParameter(0, declarationDate)
            .setHint("org.hibernate.cacheable", true)
            .unwrap(NativeQuery.class)
            .addScalar("mydate")
            .getResultList()

并得到与

类似的错误

别名的预期长度为0;实际长度是1

然后我尝试了

em.createNamedQuery("MyClass.findMyStuff", Tuple.class)
            .setParameter(0, declarationDate)
            .setHint("org.hibernate.cacheable", true)
            .unwrap(NativeQuery.class)
            .addScalar("mydate", new DateType())
            .getResultList()

BAAAAAAM终于开始工作了。

总而言之,它开始工作,然后我将查询展开为NativeQuery并添加了标量 有类型!!

请注意,如果您的本机查询没有别名,请添加别名!!!

相关线程(仅举几例)

https://hibernate.atlassian.net/browse/HHH-9111

Hibernate Ehcache NOT working for SQL Native query cache

https://csharp.developreference.com/article/10137305/Cacheable+JPA+Native+Query+IlligalStateException+%E2%80%9Caliases+expected+length+is+0%3B+actual+length+is+1%E2%80%9D

Hibernate query cache applicable for native queries?

Cache JPA Native Query

希望此解决方案可以帮助其他迷路的人。

LOL ...必须创建这个一次性帐户才能发布此答案