具有命名参数的本机查询失败,并显示“未设置所有命名参数”。 [英] Native query with named parameter fails with "Not all named parameters have been set"

查看:467
本文介绍了具有命名参数的本机查询失败,并显示“未设置所有命名参数”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行一个简单的本机查询,但它不起作用:

  @Autowired 
私有EntityManager EM;

Query q = em.createNativeQuery(SELECT count(*)FROM mytable where username =:username);
em.setProperty(username,test);
(int)q.getSingleResult();

为什么我会得到这个异常?

  org.hibernate.QueryException:并非所有命名参数都已设置:[username] 


<在本机查询中,JPA不支持命名参数,仅用于JPQL。您必须使用位置参数。


命名参数遵循4.4.1节中定义的标识符的规则。命名参数的使用适用于Java持久性查询语言,并且未针对本机查询定义。 只有位置参数绑定可以用于本机查询。


所以,使用这个

 查询q = em.createNativeQuery(SELECT count(*)FROM mytable where username =?1); 
q.setParameter(1,test);

虽然JPA规范不支持原生查询中的命名参数,但某些JPA实现(如 Hibernate )可能会支持它。


原生SQL查询支持位置和命名参数

然而,将您的应用程序连接到特定的JPA实现,从而使其不可移植。


I want to execute a simple native query, but it does not work:

@Autowired
private EntityManager em;

Query q = em.createNativeQuery("SELECT count(*) FROM mytable where username = :username");
em.setProperty("username", "test");
(int) q.getSingleResult();

Why am I getting this exception?

org.hibernate.QueryException: Not all named parameters have been set: [username]

解决方案

Named parameters are not supported by JPA in native queries, only for JPQL. You must use positional parameters.

Named parameters follow the rules for identifiers defined in Section 4.4.1. The use of named parameters applies to the Java Persistence query language, and is not defined for native queries. Only positional parameter binding may be portably used for native queries.

So, use this

Query q = em.createNativeQuery("SELECT count(*) FROM mytable where username = ?1");
q.setParameter(1, "test");

While JPA specification doesn't support named parameters in native queries, some JPA implementations (like Hibernate) may support it

Native SQL queries support positional as well as named parameters

However, this couples your application to specific JPA implementation, and thus makes it unportable.

这篇关于具有命名参数的本机查询失败,并显示“未设置所有命名参数”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆