可以使用单例DAO对象吗? [英] Is it OK to have singleton DAO objects?
问题描述
请考虑以下类的结构:
-
BaseDAO
,其方法包含峰值PreparedStatement并从池中获取连接 -
AccountDAO extends BaseDAO
通过JDBC与Account
表一起使用.这个班是单身人士 -
AccountService
像这样调用AccountDAO的方法:AccountDAO.getInstance().login(name, password).
BaseDAO
with methods to crest PreparedStatement and get connection from poolAccountDAO extends BaseDAO
to work withAccount
table via JDBC. This class is singletonAccountService
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屋!