JPA 本机查询获取单个对象

JPA Native query get a Single Object

如何使用 JPA 本机查询获取单个对象。我做了一些研究,但所有答案都是使用 "getSingleResult",但它没有 return 我想要得到的。例如,如果我想在我的数据库中获取 table 的计数并将其提取为 Integer.

我应该怎么做

下面的代码显示了我如何通过使用 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 中的表现:

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

显然,代码并不return我想要的。因此,请帮我解决这个问题。谢谢!

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

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 个对象的计数

希望对您有所帮助。

如果本机查询具有多个 select 表达式 returns 和 Object[](或 List<Object[]>)。

您可以根据需要使用下面的示例代码。

Query q = em.createNativeQuery("SELECT id,name FROM user WHERE id = ?1");
q.setParameter(1, userId);
Object[] result = (Object[])q.getSingleResult();
String id= result[0];
int name = result[1];

您可能需要对结果 Array 值进行类型转换。

这可能对某人有所帮助。 要获取单个对象,您可以选择以下任一项:

方法一:

Query theQuery = entityManager.createNativeQuery("SELECT * from yourTable where yourTableId = (Select MAX(yourTableId) from yourTable where empId = ?1 and instId = ?2 GROUP BY empId,instId)",YourTableEntity.class);
theQuery.setParameter(1, empId);
theQuery.setParameter(2, instId);
System.out.println(theQuery.getSingleResult()); 

方法二:

Query theQuery = entityManager.createNativeQuery("SELECT * from yourTable where empId = ?1 and instId = ?2 order by yourTableId DESC");   
theQuery.setParameter(1, empId);
theQuery.setParameter(2, instId);
theQuery.setMaxResults(1); //Use if it makes good impact in complexity
System.out.println(theQuery.getResultList().get(0));

注意:为了简单起见,我只是打印了它。您可能需要进行类型转换。 检查方法 1 或方法 2 所花费的时间是否更适合您。