许多类引用数据库连接类的最佳方法 [英] Best way for many classes to reference a database connection class

查看:101
本文介绍了许多类引用数据库连接类的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很快就要开始我的课程的开发阶段,目前的设计是有一个处理数据库连接的类和许多调用它的类;数据库类应该打开连接并盲目地传递查询,其他类负责这些查询的内容。

I'm soon going to be starting the development stage of my coursework and the current design is to have a single class that handles database connections and many classes that call it; the database class is supposed to open the connection and pass queries along blindly, other classes are responsible for the contents of those queries.

我想知道的是什么是这些参考知道数据库类的最好方法?我的直觉是使Database类中的方法静态,并将它们称为Database.method(),但是有更好的方法吗?

What I want to know is what is the best way for these reference to know about the database class? My instinct would be to make the methods in the Database class static and call them as Database.method() but is there a better way?

是引用正确的词吗?

推荐答案

谨慎。

Singleton将是一个瓶颈。

Singleton will be a bottleneck.

java.sql.Connection不是线程安全的,所以你可能遇到问题。

java.sql.Connection is NOT thread safe, so you could run into issues there.

d建议您将应用程序与服务和持久层完全分开。两者都应基于接口。服务层是知道工作和事务单元的层,使用模型和持久性对象来实现它们。该服务应负责获取Connection,使其可用于持久层,处理事务并在创建它的相同方法范围内关闭Connection。

I'd recommend writing your app with service and persistence layers completely separated. Both should be based on interfaces. The service layer is the one that knows about units of work and transactions, using model and persistence objects to fulfill them. The service should be responsible for acquiring the Connection, making it available to the persistence tier, handling transactions, and closing the Connection in the same method scope in which it was created.

范围和清理是关键。如果你不这样做,你将耗尽数据库连接。

Scope and cleanup are key. If you don't do this, you'll exhaust the database connections.

你没有提到连接池。我会推荐一个。

You don't mention connection pools. I'd recommend one.

看看Spring。它的JDBC模块处理所有这些美丽。如果你不能使用Spring作为你的任务,至少它将是一个很好的模型,如何设计你的实现。

Have a look at Spring. Its JDBC module handles all this beautifully. If you can't use Spring for your assignment, at least it'll be a good model for how to design your implementation.

这篇关于许多类引用数据库连接类的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆