如何在数据源动态变化时设计DAO [英] How to design DAOs when the datasource varies dynamically

查看:119
本文介绍了如何在数据源动态变化时设计DAO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常在定义DAO时,您将拥有DAO对象上数据源的setter。
我的问题是我们的数据源根据对服务器的请求动态变化。即每个请求都可以访问不同的数据库实例。

Usually when defining a DAO, you would have a setter for the datasource on the DAO object. My problem is that our datasource varies dynamically based on the request to the server. i.e. every request can access different database instance.

请求包含逻辑属性,稍后可用于检索与请求的DB的连接。

The request holds logical properties, that later can be used to retrieve the connection to the DB of the request.

因此,当依赖项将DAO注入业务逻辑对象时,我需要一种在运行时(而不是配置时)在DAO上设置属性的方法。

So when dependency injecting the DAO to the business logic object, I need a way to set the properties on the DAO at runtime (not configuration time).

一种解决方案是将数据源存储在本地线程上,但我真的不喜欢弄乱线程局部变量。

One solution is to store the datasource on the thread local, but I don't really like messing with thread local variables.

另一个选择是在业务逻辑对象上有一个初始化方法,该方法使用请求属性调用DAO上的初始化。

Another option is to have an initialize method on the business logic object that calls initialize on the DAO with the request properties.

我想这是一个常见的问题,你能建议一个共同的解决方案吗?

I guess it's a common problem, can you suggest a common solution?

推荐答案

听起来你的问题是那个您正在为您的应用程序创建一个DAO实例。您需要为每个数据源创建一个单独的实例(可能需要使用某种dao控制器来为您管理它)或者可能允许您的dao中的方法是静态的,并传递有关如何连接到数据源的所有信息以及你坚持进入每种方法的数据。

It sounds like your problem is that you are creating a single DAO instance for your application. You either need to create a separate instance for each datasource (maybe making some kind of dao controller to manage it all for you) or possibly allow your methods in your dao to be static and pass all information about how to connect to the datasource along with the data you are persisting into every method.

这篇关于如何在数据源动态变化时设计DAO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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