简体   繁体   English

如何在没有实体和 JPA 存储库的 Spring 中运行本机 SQL 查询?

[英]How to run a native SQL query in Spring without an entity and a JPA Repository?

I am trying to run some native SQL queries in my Spring application.我正在尝试在我的 Spring 应用程序中运行一些本机 SQL 查询。 I don´t have an entity or JpaRepository class.我没有实体或JpaRepository class。 I know it's strange, but this is a microservice just to collect two count queries and send it to Kafka.我知道这很奇怪,但这是一个仅用于收集两个计数查询并将其发送到 Kafka 的微服务。

Well trust me, all I need is these two integers from the queries.相信我,我需要的只是查询中的这两个整数。 I run these code and always returns 0. I can see in the logs that Hikari is connecting to the database, so I don't know what to do.我运行这些代码并总是返回 0。我可以在日志中看到 Hikari 正在连接到数据库,所以我不知道该怎么办。 Searched a lot, but all answers involved the @Query solution, which does not work for me.搜索了很多,但所有答案都涉及@Query解决方案,这对我不起作用。

@Repository
@AllArgsConstructor
public class ReportRepository {


  private final EntityManager em;

  public int numberOfAccounts() {
    String sql = "SELECT count(*) FROM account";
    Query query = em.createNativeQuery(sql);
    System.out.println(query.getFirstResult());
    return query.getFirstResult();
  }

  public int numberOfSubscriptions() {
    String sql = "SELECT count(*) FROM subscriptions";
    Query query = em.createNativeQuery(sql);
    System.out.println(query.getFirstResult());
    return query.getFirstResult();
  }
}

If you have EntityManager , and from what you are saying it can connect to DB, try this way:如果您有EntityManager ,并且按照您所说的可以连接到数据库,请尝试以下方法:

public int numberOfSubscriptions() {
    // >> "subscriptions" has to be the exact name of your table
    // if does not work, consider trying SUBSCRIPTIONS or Subscriptions
    String sql = "SELECT count(*) FROM subscriptions";
    Query query = em.createNativeQuery(sql);

    // getSingleResult() instead :)
    return ((Number) query.getSingleResult()).intValue();
}

There is this (a bit old) JavaDoc for Query.getFirstResult() : Query.getFirstResult()有这个(有点旧)JavaDoc:

The position of the first result the query object was set to retrieve.查询 object 设置为检索的第一个结果的 position。 Returns 0 if setFirstResult was not applied to the query object如果 setFirstResult 未应用于查询 object,则返回 0

So, I'd say that is not the right method for your case.所以,我会说这不是你的情况的正确方法。

Happy Hacking:)快乐黑客:)

You should be using JDBC instead of an Entity Manager.您应该使用 JDBC 而不是实体管理器。 Under the JPA uses JDBC but it requires defined entites to work.在 JPA 下使用 JDBC 但它需要定义的实体才能工作。 JDBC allows you to manage the connection and run the raw SQL queries. JDBC 允许您管理连接并运行原始 SQL 查询。

Here's a link for how to do it in Spring: https://spring.io/guides/gs/relational-data-access/#_store_and_retrieve_data这是如何在 Spring 中执行此操作的链接: https://spring.io/guides/gs/relational-data-access/#_store_and_retrieve_data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM