jpa本机查询获取单个对象

px9o7tmv  于 2021-07-13  发布在  Java
关注(0)|答案(3)|浏览(316)

如何使用jpa本地查询获得单个对象。我做了一些研究,但给出的答案都是使用“getsingleresult”,但它没有返回我想要的结果。例如,如果我想在数据库中获取表的计数并将其取为整数,我应该怎么做。
下面的代码显示了如何使用session 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());

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

6fe3ivhb

6fe3ivhb1#

对于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 object的count
希望它能对你有所帮助。

41zrol4v

41zrol4v2#

如果本机查询包含多个select表达式,则返回 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 价值观。

cdmah0mi

cdmah0mi3#

这可能对某人有帮助。要获取单个对象,可以选择以下任一选项:
方法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所花费的时间是否更适合您。

相关问题