为什么我们使用 DataSource 而不是 DriverManager? [英] Why do we use a DataSource instead of a DriverManager?

查看:26
本文介绍了为什么我们使用 DataSource 而不是 DriverManager?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Java JDBC 规范 (vr. 4) 并且我遇到了以下声明:

<块引用>

DataSource — 这个接口是在 JDBC 2.0 Optional 中引入的包 API.它比 DriverManager 更受欢迎,因为它允许有关底层数据源的详细信息对申请

我想了解的是 ConnectionDataSource,以及它存在的原因.我的意思是,上面的块说有关数据源的详细信息对应用程序是透明的,但是不会在属性文件中将数据库属性(例如用户名、密码、url 等)外部化,然后使用 DriverManager 以相同的方式工作吗?

DataSource 接口创建只是为了有一个通用的方式来返回可以汇集等的连接?在 Java EE 中,应用程序服务器是否实现了这个接口,并且部署的应用程序是否引用了数据源而不是连接?

解决方案

更好的可扩展性和维护性

对于DriverManager,您需要知道所有详细信息(主机、端口、用户名、密码、驱动程序类)才能连接到数据库并获取连接.将属性文件中的内容外部化并不会改变您需要了解它们的事实.

使用 DataSource 您只需要知道 JNDI 名称.AppServer 关心细节,不是由客户端应用程序的供应商配置,而是由托管应用程序的管理员配置.

可扩展性:

假设您需要自己创建连接,您将如何处理不断变化的负载,有时您有 10 个用户,有时您有 1000 个,您不能在需要时就获得连接,然后释放"它以便数据库服务器不会退出连接,这会导致您进入连接池.DriverManager 不提供,DataSource 提供.

如果您要自己编写连接池,则必须使用DriverManager,否则使用DataSource.

I am reading the Java JDBC specification (vr. 4) and I encountred this statement:

DataSource — this interface was introduced in the JDBC 2.0 Optional Package API. It is preferred over DriverManager because it allows details about the underlying data source to be transparent to the application

What I am trying to understand is what the difference is between a Connection and a DataSource, and why it exists. I mean, the block above says that the details about a datasource is transparent to the application, but wouldn't externalizing database properties such as username, password, url etc in a property file and then use DriverManager work in the same way?

And is the DataSource interface created only to have a common way of returning connections that can be pooled etc? In Java EE, does the application server implement this interface and the applications deployed to have a reference to a datasource instead of a connection?

解决方案

Better scalability and maintenance

For DriverManager you need to know all the details (host, port, username, password, driver class) to connect to DB and to get connections. Externalizing those in a properties file doesn't change anything about the fact that you need to know them.

Using a DataSource you only need to know the JNDI name. The AppServer cares about the details and is not configured by the client application's vendor, but by an admin where the application is hosted.

Scalability:

Suppose you need to create connections yourself, how would you deal with changing load, sometime you have 10 users sometime you have 1000, you can't just get a connection whenever you need one and later 'release' it so the Database server does not get out of connections, which leads you to connection pooling. DriverManager does not provide it, DataSource does.

If you are going to program a connection pool yourself then you have to use DriverManager, otherwise go with DataSource.

这篇关于为什么我们使用 DataSource 而不是 DriverManager?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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