【问题标题】:JPA Native query get a Single ObjectJPA Native 查询获取单个对象
【发布时间】:2016-03-28 03:12:02
【问题描述】:

如何使用 JPA Native 查询获取单个对象。我做了一些研究,但都给出了答案是使用“getSingleResult”,但是它没有返回我想要得到的东西。例如,如果我想在我的数据库中获取表的计数并将其提取到 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()); 

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

【问题讨论】:

  • 这似乎是一个查询,您可以使用 JPQL for ...

标签: java mysql hibernate jpa jpql


【解决方案1】:

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

希望对你有所帮助。

【讨论】:

  • 您好,感谢您的回复。这将返回正确的结果。但我希望的是一种方法来获取我从数据库中查询的对象的值。如果我想得到这样的对象,我应该怎么做:“从 table_test 中选择名称,其中 id = 1”。
  • 你需要像我编辑的答案那样做 String name = this.entityManager.createNativeQuery("select t.name from your_table_name t limit 1").getSingleResult().toString();
  • 嗨拉维,很抱歉回复晚了。效果很好,非常感谢
【解决方案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 值。

【讨论】:

  • 如果查询 JPA 没有结果,则抛出 NoResultException。
【解决方案3】:

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

方法一:

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 所花费的时间是否更适合您。

【讨论】:

    猜你喜欢
    • 2011-02-19
    • 2011-01-22
    • 1970-01-01
    • 2021-05-03
    • 2023-02-17
    • 1970-01-01
    • 2016-06-21
    • 2011-09-10
    • 1970-01-01
    相关资源
    最近更新 更多