JPA本机查询获取单个对象 [英] JPA Native query get a Single Object
问题描述
如何使用JPA本机查询获取单个对象.我做了一些研究,但全部给出的答案是使用"getSingleResult",但是它没有返回我想要的结果.例如,如果我想获取数据库中的表计数并将其提取到Integer中,该怎么办.
How can i get a single object by using JPA Native query. I did some researches but all give an answer is use "getSingleResult", however it didn't return what i want to get. For example, what should i do if i want to get a count of table in my database and fetch it into a Integer.
下面的代码显示了我如何通过使用Sessison休眠方式来获取此信息:
This code below shows how i get this by using Sessison hibernate:
int check = Integer.parseInt((String) sessionF.createSQLQuery("select to_char(count(*)) as count from user_tables where table_name upper('TEST')").uniqueResult());
我希望在JPA中能做到的事
And what i hope to be fine in JPA:
int check = Integer.parseInt((String) getEntityManager().createNativeQuery("select to_char(count(*)) as count from user_tables where table_name upper('TEST')").getSingleResult());
很显然,代码没有返回我想要的.因此,请帮助我解决这个问题.谢谢!
Obviously, the code doesn't return what i want. Therefore, please help me to cope with this problem. Thank you !
推荐答案
使用JPA,您需要执行以下操作
With JPA you need to do like following
int num = ((Number)this.entityManager.createNativeQuery("select count(*) from your_table_name")
.getSingleResult()).intValue();
已
String name = this.entityManager.createNativeQuery("select t.name from your_table_name t limit 1").getSingleResult().toString();
您将获得num个对象的计数
you will got count with num object
希望它会对您有所帮助.
Hope its will help to you.
这篇关于JPA本机查询获取单个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!