对于中等复杂的 Java 桌面应用程序; JavaDB 连接应该是静态的吗?
我正在编写一个中等复杂的 Java 桌面应用程序,包括一个嵌入式数据库。我不明白为什么在应用程序建立与数据库的连接后,为什么它应该关闭连接,直到应用程序要关闭。
实际上,人们对数据库所做的一切都需要连接;事务可以在连接中串行启动和完成,应用程序不会对数据库执行任何极其复杂的操作。
有什么理由为什么我不应该创建连接并将对它的引用放入数据库特定类已知和使用的类中的静态变量中?这将节省必须在各种方法之间传递连接而不改变值的情况。
我是否在某处遗漏了设计层面的考虑?
RC
I am writing a moderately complex Java desktop app, including an embedded database. I do not see any reason why, after the app establishes a connection to the database, why it should close the connection until the app is going to shut down.
Practically everything one does with the database requires a connection; transactions can be started and completed serially in the connection, the app is not doing anything fantastically complicated with the database.
Is there any reason why I should not create the connection and put a reference to it in a static variable in a class known and used by database-specific classes? It would save having the connection have to be passed around among all kinds of methods without ever changing value.
Is there a design-level consideration I'm missing somewhere?
rc
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议使用诸如
c3p0
或dbcp
为您处理连接池。它使您可以在必要时灵活地扩展您的应用程序。任何
静态
通常都会使编写正确的测试用例变得困难,因为您永远不知道静态资源是否已被更改。I would suggest using a library such as
c3p0
ordbcp
which handles connection pooling for you. It gives you the flexibility to scale up your application later if necessary.Anything
static
usually makes it harded to write proper test cases, since you never know if the static resource has been altered or not.三个月后,您将希望能够同时连接到两个数据库 - 也许您正在做一些导入/导出工作,或者升级工作,或者将两个客户合并在一起。然后你会想要其中两个。现在突然间每个人都使用的静态场变成了一场噩梦。
您可以查看 IoC 容器,例如 Guice 或 Spring 确保您可以跟踪“单例”对象,而不会滥用静态字段来强制其“单例”性。
Three months down the road, you're going to want to be able to connect to two databases at the same time - maybe you're doing some import / export work, or an upgrade job, or merging two customers together. And then you're going to want two of them. And now suddenly that static field everyone uses is a nightmare.
You could look into an IoC container like Guice or Spring to ensure that you can keep track of "singleton" objects without abusing static fields to enforce their "Singleton"ness.
避免静电。考虑此类变量的并发和多线程问题。一个好处是处理与数据库池的连接。 Spring 是您实现简单而漂亮的配置的朋友
Avoid statics. Think on concurrency and multithread issues with this kind of variables. A good point is handle your connections with a database pool. Spring is your friend to reach a simple and nice configuration
这对我来说似乎完全没问题。它是一个嵌入式数据库;这是在服务中
您的申请。启动时创建连接,只要您使用它
需要时,请在应用程序关闭时将其关闭。
That seems completely fine to me. It's an embedded database; it is at the service
of your application. Create the connection when you start, use it as long as you
need, shut it down when your application closes down.