java - 负责数据库上的 CRUD 操作的类的最佳设计是什么?
问题描述
我想创建一个类User
来操作user
数据库中表上的数据。但我不知道是否应该将其设为 Singleton 或只是捆绑一堆静态方法。
class UserSingleton {
private static instance;
private UserSingleton() {
// stablish connection and prepare statements
}
public static getInstance() {
if (instance == null) {
instance = new UserSingleton();
}
return instance;
}
public void create() {};
public void delete() {};
// and so on...
}
class UserStatic {
public static initialize() {
// Stablish connection and prepare statements.
// These properties would be static.
}
public static void create() {};
public static void delete() {};
// and so on...
}
我真的不知道这里最好的方法是什么,也不知道它们各自的优缺点。虽然单例类看起来更加优雅和酷,但静态类 API 会更容易使用,因为我不必实例化对象。它也类似于我的猫鼬,其中这些方法是静态的,例如:Model.create()
, Model.findById()
, 等等......
你怎么看?还是我应该以完全不同的方式来做?关于应用程序的一些上下文:
- 这是一个使用 JavaFX 制作的中小型桌面应用程序
- 数据库是 SQLite
- 测试不是优先事项(有些人可能会指出 Singleton 不好,因为它使测试更难)
解决方案
看看 JPA、Spring Data with eclipselink as implementation 或 Hibernate。如果只是出于教育目的,请查看 spring orm implementationaions。
推荐阅读
- javascript - 如何使此页面中的所有 EventListener 工作?
- r - 从 SpatialPointsDataFrame 中的每个点到第二个 shapefile 中最近的点/线的最快笛卡尔距离 (R)
- python-3.x - WinError 10022:提供了一个无效的参数,我不知道为什么
- python - Python 无法将消息添加到 Thunderbird Mbox
- javascript - 如何取消订阅嵌套的实时 Firebase Cloud Firestore 数据库?
- c++ - 在 Windows 上使用带有 Cxx.jl 的 Julia 中的 boost 库
- python - 函数在应该返回最后一个索引时返回 None
- ios - UIView 动画不起作用 - Xcode (Swift)
- php - 如何将 PHP 对象转换为 C++ 对象
- ios - 如何在颤动的列表底部显示一个按钮?