开发者

Spring, Hibernate: DAO-Class: Using always the same object?

Im working with Spring 3 and Hibernate 3.6 on developing a webapplication.

I have a DAO-Class and I created in a xml-file ONE bean (named "dao1") for it. Every class which needs to access the database get this instace injected. It is ALWAYS the same dao-object (scope=singleton)

Now I wonder if this is a recommended way of using a DAO. Would it be better to inject always different instances in other classes and if yes, why? Would it also be better to split the DAO in different classes containing always some dao-methods, maybe specific for one table?

are there any disadvantages when I use the structure I mentioned?

开发者_如何学Go

thank you! :-)


With Hibernate / JPA, the dao requires a fresh session/entity manager. But spring handles that by injecting a proxy which locates the fresh session each time. So having a singleton DAO is the proper way to go.

To clarify - if you DAO does not hold any state (i.e. doesn't have instance fields) apart from injected dependencies, then it can safely be singleton. Otherwise - not.


As a rule of thumb when working with injections is to ask yourself.

Are there any state in this component/bean/object ?

If there are state that has to be handled per call or whatever, you need to alter the scope or lifecycle. If not, then you should configure it as singleton.

And generally in a DAO class, there are no state. Or shouldn't be. The state should be in the persistence target (the database).

Therefore it's a pretty safe guess to say that you are perfectly fine configuring it as Singleton in this case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜