开发者

JDBC MVC - Ways of sharing DB connection instances in Repositories methods

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 ou开发者_JS百科tside 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...


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜