JPA 本机查询获取单个对象

min*_*inh 5 java mysql hibernate jpa jpql

如何使用 JPA Native 查询获取单个对象。我做了一些研究,但都给出了一个答案是使用“getSingleResult”,但是它没有返回我想要的。例如,如果我想在我的数据库中获取表的数量并将其提取到一个整数中,我该怎么办。

下面的代码显示了我如何通过使用 Sessison 休眠来实现这一点:

int check = Integer.parseInt((String) sessionF.createSQLQuery("select to_char(count(*)) as count from user_tables where table_name upper('TEST')").uniqueResult()); 
Run Code Online (Sandbox Code Playgroud)

我希望在 JPA 中一切顺利:

int check = Integer.parseInt((String) getEntityManager().createNativeQuery("select to_char(count(*)) as count from user_tables where table_name upper('TEST')").getSingleResult()); 
Run Code Online (Sandbox Code Playgroud)

显然,代码没有返回我想要的。因此,请帮助我解决这个问题。谢谢 !

Rav*_*iya 5

使用 JPA,您需要执行以下操作

int num = ((Number)this.entityManager.createNativeQuery("select count(*) from your_table_name")
                .getSingleResult()).intValue();
Run Code Online (Sandbox Code Playgroud)

编辑:

 String name = this.entityManager.createNativeQuery("select t.name from your_table_name t limit 1").getSingleResult().toString();
Run Code Online (Sandbox Code Playgroud)

你会得到 num 对象的计数

希望它会对你有所帮助。