在桌面客户端-服务器应用程序中减少 Hibernate repositories/using Spring 的 JpaRepository 接口中的样板代码

Reducing boilerplate code in Hibernate repositories/using Spring's JpaRepository interface in a desktop client-server application

我目前正在开发使用 Hibernate 访问数据库的桌面 Java 客户端-服务器应用程序。许多对数据库的调用都是通用的 CRUD 操作,因此我喜欢一种减少样板代码量的方法。

我偶然发现了 Spring 框架中的 JpaRepository/CrudRepository 接口,并希望能够使用它们中的任何一个,但感觉好像我一直在与 Spring 的网络应用程序焦点。例如,由于存储库由 Spring 自动连接,我无法实例化副本或创建静态实例,因此很难从服务器 class 调用存储库的任何方法。

因此我有四个问题:

  1. 有没有办法使用 Spring Jpa/CrudRepository 接口 没有自动装配它们?
  2. 有没有办法在不使用 Spring 的情况下使用任一界面?
  3. 是否有可实现相同目的的桌面应用程序替代界面?
  4. 有没有我缺少的更好的选择?

chrylis 在评论中给了你真正需要的答案:

Make your "program" a Spring component

我认为适当的方法是将其设为 CommandLineRunner

我什至会说:即使你在一个进程中启动你,你也应该维护一个类似 web 的架构,甚至可能是应用程序中的一个 web 服务器,以便

a) 以合理的方式使用 JPA,即明确定义由服务器进程在单独的线程中处理的请求

b) 在处理查询时不要阻塞 UI。

回答你的字面问题:

Is there a way to use the Spring Jpa/CrudRepository interfaces without autowiring them in?

是的,您可以使用 JpaRepositoryFactory

手动创建存储库

Is there a way to use either interface without using Spring?

接口本身只是接口,可以在 Spring 没有任何其他东西的情况下使用。 当然,这样做的好处是有限的。

Is there an alternative interface for desktop applications which would achieve the same purpose?

不,没有必要。

Is there a better alternative that I'm missing.

我不这么认为,但我有偏见。