JDBC MVC - 在存储库方法中共享数据库连接实例的方法

发布于 2024-12-09 00:45:08 字数 330 浏览 2 评论 0原文

我正在构建一个基于 MVC 的 Web 应用程序,每个模型聚合都有它自己的存储库。存储库从 MySQL 数据库获取数据。

我很难决定如何实现各种存储库方法,主要是因为我希望能够在同一个数据库连接中执行顺序查询(而不是在每个方法主体中创建一个新连接,然后在方法结束)。

在两个顺序存储库方法之间共享数据库连接实例的一种方法是将已创建的数据库连接的实例(在存储库外部创建)作为存储库方法的参数传递。 显然,这个实现在设计上完全错误。

另一种方法是拥有存储库将使用的单例数据库连接池或某种工厂,并且可以根据需要选择专门创建新连接。

我想知道你们对于上述问题是否还有其他设计技巧......

I'm building an MVC based web application, each Aggregate of Models has it's own Repository. The repositories fetch the data from a MySQL database.

I'm having an hard time deciding how to implement the various repositories methods, mainly because I want to be able to perform sequential queries in the same database connection (as opposed to creating a new connection in each method body, and closing it at the end of the method).

One way to share a db connection instance between two sequential repository methods, would be to pass an instance of an already created DB Connection (which is created outside the repository) as an argument for the repository method.
Obviously, This implementation smells totally wrong design-wise.

A different approach would be having a singleton DB Connection Pool or a Factory of some sort which the repositories will use, and have the option for specifically create a new connection if desired.

I was wondering if you guys have any other design tips for the above issue...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

滥情哥ㄟ 2024-12-16 00:45:08

这一切都解决了。不要自己写。使用提供数据源实现的连接池库,例如 DBCP。这负责连接重用。使用 Spring 的 JdbcTemplate 为您处理所有的打开和关闭。然后应用声明式事务管理除此之外,您将有效地获得每个请求的连接。

This is all solved. Don't write it yourself. Use a connection pooling library that provides a DataSource implementation like DBCP. That takes care of connection reuse. Use Spring's JdbcTemplate to handle all the opening and closing for you. Then apply declarative transaction management on top of it, and you'll effectively get a connection-per-request.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文