3

我需要编写一个基于守护程序的 Java 进程(不是基于 Web),它将连接到 Oracle 10G 数据库,从中读取一些数据,然后连接到 SQL Server 数据库并将数据写入表。

听起来很简单,但我对此有几个疑问。

  • 我需要有两个 jdbc 驱动程序,即一个用于连接到 Oracle 数据库,另一个用于连接到 sql server 数据库。sql server jdbc 驱动程序是 jtds jdbc 驱动程序(http://jtds.sourceforge.net/),对于 Oracle,我将使用标准的 oracle jdbc 驱动程序。我是否可能会同时遇到类路径中可用的两个驱动程序的任何问题?

  • 我的猜测是,我只需要一个 ConnectionManager 类来管理连接和一个客户端 DAO 类,该类将调用相关方法来获取所需的连接,具体取决于它是从 Oracle 读取还是写入 SQL Server。这是一种合理的方法还是有更好的设计/模式?

编辑

好的,我试图组合一个快速的设计解决方案。见下图

我认为我遇到的问题是如何提交。下面是处理流程

  • InvoiceBD 从工厂类获取 Oracle 连接,并调用 InvoiceUploadDAO.readData 将 Oracle 连接对象传递给它。
  • InvoiceBD 从工厂类获取 SQL Server 连接并调用 InvoiceUploadDAO.writeData 将 SQL Server 连接对象传递给它。
  • InvoiceBD 重用 Oracle 连接来调用 InvoiceUploadDAO.update 状态为 Oracle 数据库上的“完成”设置状态。

InvoiceBD 提交 Oracle 连接。InvoiceBD 提交 SQL Server 连接。

或者,如果出现问题,两个连接对象都会回滚。

那个听起来是对的吗?

谢谢

4

2 回答 2

4

我是否可能会同时遇到类路径中可用的两个驱动程序的任何问题?

Unlikely. The DriverManager.getConnection method actually delegates the construction of the connection to all drivers registered with it. Only drivers that recognize the protocols in the JDBC URL will return the connection. The JDBC specification states:

When the DriverManager is trying to establish a connection, it calls that driver’s connect method and passes the driver the URL. If the Driver implementation understands the URL, it will return a Connection object; otherwise it returns null.

...

The format of a JDBC URL is :

jdbc:<subprotocol>:<subname>

In the case of both jTDS and the Oracle (thin) driver, the protocol formats are different, and hence, you would never experience a problem. However, remember not to place more than one version of the same driver.

Is this a reasonable approach or is there a better design/pattern for this?

You are looking for a DataSource. DataSources would have been availble in a Java EE environment, and not in Java SE applications. You can however, build your own DataSource or a similar class; you don't need to implement the DataSource interface itself, but you could do something similar. In your context, the ConnectionManager class of yours will assume the role of the DataSource by possibly accepting a parameter that distinguishes which database to connect to; you could think about using a connection pool in case you need one (unlikely if you need only one connection to the database).

You could also adopt @duffymo's approach of building DAO classes, although it is better suited for a situation where the SQL queries are different.

于 2011-06-18T17:29:54.290 回答
3
  1. 类路径中的两个驱动程序都没有问题。如果您需要将读取和写入作为单个事务,您可能需要考虑同时使用 XA 驱动程序。如果您需要两阶段提交,您将需要两者的 XA 驱动程序。
  2. 您需要两个 DAO 实例,一个用于 Oracle 读取,另一个用于 SQL Server 写入。
于 2011-06-18T16:32:48.107 回答