JPA Native查询获取单个对象

时间:2016-03-28 03:12:03

标签: java mysql hibernate jpa jpql

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

下面这段代码展示了我如何通过使用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()); 

显然,代码不会返回我想要的内容。因此,请帮我解决这个问题。谢谢!

3 个答案:

答案 0 :(得分:4)

使用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对象的数量

希望它会对你有所帮助。

答案 1 :(得分:2)

如果使用多个选择表达式进行本机查询,则返回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值进行类型转换。

答案 2 :(得分:0)

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

方法1:

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()); 

方法2:

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所花费的时间是否对您来说更好。