可以使用单例DAO对象吗? [英] Is it OK to have singleton DAO objects?

查看:137
本文介绍了可以使用单例DAO对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下类的结构:

  1. BaseDAO,其方法包含峰值PreparedStatement并从池中获取连接
  2. AccountDAO extends BaseDAO通过JDBC与Account表一起使用.这个班是单身人士
  3. AccountService像这样调用AccountDAO的方法: AccountDAO.getInstance().login(name, password).
  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是一个带有@Transactional批注的Spring bean,用于插入一些数据的方法.

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

这样可以吗?我认为单例DAO类可能会导致性能问题.在服务层类中使用一些春季注入更好吗? (我是Spring的新手,所以任何建议都将适用)

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)

推荐答案

Spring文档中推荐的方法是将DAO编写为普通类并使用单例作用域.如果您的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

第3.4.2节

如果您使用的是Spring,则无需处理准备好的语句,而不必做什么,除非您做的事情很奇怪.查看JdbcTemplate或HibnerateTemplate.是的,您应该连接Spring以便将DAO注入到您的服务中或需要使用它们的任何地方.

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.

这篇关于可以使用单例DAO对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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