[英]Java native query - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException
I get following error: "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Card.findPrefix'" 我收到以下错误消息:“ com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的SQL语法有错误;请查看与您的MariaDB服务器版本相对应的手册,以在'Card.findPrefix'附近使用正确的语法”
for:
@NamedNativeQueries({
@NamedNativeQuery(name = "Card.findPrefix",
query = "SELECT DISTINCT(FLOOR(c
.number/10000)) FROM Card c")
})
public List<Integer> findPrefix(){
Query q = em.createNativeQuery("Card.findPrefix");
try{
return q.getResultList();
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}
I can not understand where is my mistake, because when I type this query directly to Mysql it works perfectly. 我不明白我的错误在哪里,因为当我直接在Mysql中键入此查询时,它可以很好地工作。
Use should use createNamedQuery, instead of createNativeQuery. 使用时应使用createNamedQuery而不是createNativeQuery。
From EntityManager JavaDoc 从EntityManager JavaDoc
createNativeQuery(String sqlString) createNativeQuery(String sqlString)
Create an instance of Query for executing a native SQL statement, eg, for update or delete. 创建用于执行本机SQL语句(例如,用于更新或删除)的Query实例。
createNamedQuery(String name) createNamedQuery(字符串名称)
Create an instance of Query for executing a named query (in the Java Persistence query language or in native SQL). 创建用于执行命名查询的Query实例(使用Java Persistence查询语言或本机SQL)。
So in your code you are executing query name 'Find....' as SQL query. 因此,在您的代码中,您正在执行查询名称“ Find ....”作为SQL查询。
The right one: 正确的那一个:
Query q = em.createNamedQuery("Card.findPrefix");
Final code is: 最终代码是:
public List<Integer> findPrefix(){
Query q = em.createNamedQuery("Card.findPrefix");
List<Integer> res = new ArrayList<Integer>();
for(Object row : (List<Object>) q.getResultList()){
res.add(((BigInteger)row).intValue());
}
return res;
}
@NamedNativeQueries({
@NamedNativeQuery(name = "Card.findPrefix",
query = "SELECT DISTINCT(FLOOR(c.number/10000)) FROM Card c")
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.