设计一个 hibernate dao
我正在使用以下代码
TestDAO {
Session session = null;
public TestDAO() {
this.session = HibernateUtil.getSessionFactory().getCurrentSession();
}
//...more code create,update ...
//each method starts a transcation using "tx= session.beginTransaction();"
}
1)现在我应该使用 tx.commit 提交交易以进行提取操作还是仅用于保存/更新操作?
2)我应该每次需要时创建一个单独的 TestDAO 实例吗?还是应该创建一个每次都返回单个 DAO 实例的单例类?这会有问题吗?
I am using following code
TestDAO {
Session session = null;
public TestDAO() {
this.session = HibernateUtil.getSessionFactory().getCurrentSession();
}
//...more code create,update ...
//each method starts a transcation using "tx= session.beginTransaction();"
}
1)Now should i commit the transcation using tx.commit for a fetch operation too or only for save/update operation??
2)Should i create a seperate instance of TestDAO every time i need?Or should i create a singleton class that returns a single instance of DAO everytme?Will this have a problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要 tx.commit() 来进行获取操作。仅当保存、更新或删除时才需要该信息。获取数据后关闭会话。
如果您的应用程序仅连接到一个数据库,那么使用单个 DAO 会更好。 Spring 框架鼓励这样做。您可以在以下链接中找到有关此内容的更多详细信息
不要重复 DAO!< /p>
You don't need tx.commit() for fetch operation. That is only needed for any save, update or delete. Close the session after data fetching.
If your application connect to only one database then use of single DAO is better. Spring framework encourages this. You will find more details about this on the following link
Don't repeat the DAO!
交易不应该是 DAO 的责任,那些确实需要在更高级别上进行控制。 DAO 应该是在不了解全局的情况下进行查询和更新的东西,对 DAO 的调用可以分组在一个对象中,例如 Spring 服务或 EJB 会话 bean,负责决定事务中需要组合在一起的内容。这使得您的 DAO 代码更具可重用性,因为它不必了解其运行的上下文。
看看 Spring 是如何做到这一点的(在 Spring 附带的 petstore 等示例应用程序中),或者更好的是,看看 King/Bauer Hibernate-JPA 书,其中有一章是关于创建 DAO 的。
Transactions should not be the responsibility of the DAO, those really need to be controlled at a higher level. A DAO should be something that does queries and updates without being aware of the bigger picture, calls to DAOs can be grouped within an object like a Spring service or EJB session bean which is responsible for deciding what needs to go together in a transaction. This makes your DAO code more reusable since it doesn't have to know as much about the context in which it's operating.
Look at how Spring does it (in the sample applications like petstore that come with Spring), or better, look at the King/Bauer Hibernate-JPA book, which has a chapter on creating DAOs.