可以使用单例 DAO 对象吗?

发布于 2024-09-28 05:04:26 字数 466 浏览 0 评论 0原文

考虑以下类的结构:

  1. BaseDAO 具有创建PreparedStatement 的方法,并从池
  2. AccountDAO 扩展BaseDAO 获取连接,以通过 JDBC 处理Account 表。这个类是单例
  3. AccountService,它调用AccountDAO的方法,如下所示: AccountDAO.getInstance().login(name,password)。

AccountDAO 是一个 Spring bean,在插入某些数据的方法中带有 @Transactional 注释。

这样可以吗?我认为单例 DAO 类会导致性能问题。也许最好在服务层类中使用一些 spring 注入? (我是 Spring 新手,所以任何建议都会被采纳)

Consider the following classes' structure:

  1. BaseDAO with methods to crest PreparedStatement and get connection from pool
  2. AccountDAO extends BaseDAO to work with Account table via JDBC. This class is singleton
  3. AccountService witch calls methods of AccountDAO like this:
    AccountDAO.getInstance().login(name, password).

AccountDAO is a Spring bean with @Transactional annotations to methods that insert some data.

Is this OK? I think singleton DAO classes can cause performance problems. May be it is better to use some spring injections into service layer classes?
(I'm new to Spring, so any advice will be appriciated)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

如若梦似彩虹 2024-10-05 05:04:26

Spring 文档中推荐的方法是将 DAO 编写为普通类并使用单例范围。如果您的 DAO 不维护任何状态,这将工作得很好。

http://static. springsource.org/spring/docs/2.0.x/reference/beans.html#beans-factory-scopes-prototype

第 3.4.2 节。

如果您使用 Spring,则不需要处理准备好的语句等,除非您正在做一些奇怪的事情。查看 JdbcTemplate 或 HibnerateTemplate。是的,您应该连接 Spring 将 DAO 注入到您的服务中或任何您需要使用它们的地方。

The recommended approach in the Spring documentation is to write your DAOs as normal classes and use the singleton scope. This will work fine if your DAOs maintain no state.

http://static.springsource.org/spring/docs/2.0.x/reference/beans.html#beans-factory-scopes-prototype

section 3.4.2.

If you are using Spring, you shouldn't need to deal with prepared statements and whatnot, unless you are doing something wonky. Look at JdbcTemplate or HibnerateTemplate. Yes, you should wire Spring to inject your DAOs into your services or wherever you need to use them.

十二 2024-10-05 05:04:26

我对 Spring 不太熟悉,但通常您不希望从多个线程访问与数据源的连接。如果您将其配置为使 DAO 对象成为线程上下文中的伪单例,但不跨线程共享,则可能没问题。大多数 IoC 容器允许您通过配置来完成此操作。

当然,这会带来有关数据一致性的其他考虑因素,您必须仔细管理这些因素。一般来说,ORM 部分会帮助你解决这个问题。

I am not too familiar with Spring but in general you don't want the connections to your data sources to be accessed from multiple threads. It is probably O.K. if you configure it so that the DAO objects are pseudo-singletons within a thread context but are not shared across threads. Most IoC containers will allow you to do this through configuration.

Of course, this brings other considerations about data consistency into play and you have to manage those carefully. Generally the ORM part will help you with that though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文