gpt4 book ai didi

java - 没有@Query的Spring存储库

转载 作者:行者123 更新时间:2023-11-29 06:27:58 24 4
gpt4 key购买 nike

我正在开发一个使用 spring 框架构建的桌面应用程序,该应用程序的一部分无法正常工作。我发现存储库类没有任何带有@Query注释的查询。我以前没遇到过。

当我尝试打开使用它的表单时,收到一条错误消息,指出应用程序无法连接到数据库。该应用程序在 application.properties 中指定了 3 个数据库。我有以下问题:

1) 如果没有使用 @Query 注释指定查询,以下代码如何工作。或者查询写在哪里。

@Repository
public interface AccountRepository extends JpaRepository<Account, Long> {

List<Account> findAccountsByActiveIsTrueAndAccountTypeEquals(String accountType);

List<Account> findAccountsByAccountTypeLike(String type);
}

2)我们如何指定要搜索哪个数据库。例如:我当前有 3 个 mysql 数据库连接到我的应用程序。我希望通过我的 Spring boot 应用程序通过通常的流程访问 DB1 中的数据UI 模型 -> BE Controller /服务层 -> 存储库(接口(interface)),其中(通常)使用 @Query 编写查询。我们如何指定该查询针对哪个数据库?

最佳答案

对于你的第一个问题,我可以回答,JpaRepository 有一个内部系统,可以分析你编写的方法名称,然后生成必须对数据库执行的查询。

当方法名称和生成的查询没有返回您想要的结果时,使用@Query注释,以便您明确告诉编译器应该执行哪个查询。

正如这里提到的:https://docs.spring.io/spring-data/jpa/docs/1.5.0.RELEASE/reference/html/jpa.repositories.html

2.3.1 Query lookup strategies. The JPA module supports defining a query manually as String or have it being derived from the method name. Declared queries Although getting a query derived from the method name is quite convenient, one might face the situation in which either the method name parser does not support the keyword one wants to use or the method name would get unnecessarily ugly. So you can either use JPA named queries through a naming convention (see Section 2.3.3, “Using JPA NamedQueries” for more information) or rather annotate your query method with @Query (see Section 2.3.4, “Using @Query” for details).

所以基本上使用命名约定就能发挥魔力。

这里还可以找到一个有趣的问题和完美的答案: How are Spring Data repositories actually implemented?

对于你的第二个问题,你可以引用这个例子:

https://www.baeldung.com/spring-data-jpa-multiple-databases

一开始可能会有点复杂,但最终会成功的。

关于java - 没有@Query的Spring存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58397614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com