可以使用单例 DAO 对象吗?
考虑以下类的结构:
BaseDAO
具有创建PreparedStatement 的方法,并从池AccountDAO 扩展BaseDAO
获取连接,以通过 JDBC 处理Account
表。这个类是单例- AccountService,它调用AccountDAO的方法,如下所示:
AccountDAO.getInstance().login(name,password)。
AccountDAO
是一个 Spring bean,在插入某些数据的方法中带有 @Transactional
注释。
这样可以吗?我认为单例 DAO 类会导致性能问题。也许最好在服务层类中使用一些 spring 注入? (我是 Spring 新手,所以任何建议都会被采纳)
Consider the following classes' structure:
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
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
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.
我对 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.