不同 dao 方法的相同代码包装
我正在阅读 hibernate 教程,注意到在每个 dao 中,您都必须获取会话,开始事务。执行所有操作,然后提交
private void createAndStoreEvent(String title, Date theDate) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
//Perform operations...
session.getTransaction().commit();
}
然后我注意到在一个名为 Appfuse 的框架中,它使用 hibernate 有如下所示的 dao 方法。我没有看到begintransaction 和 commit
public List<Person> findByLastName(String lastName) {
//begintransaction
return getHibernateTemplate().find("from Person where lastName=?", lastName);
//Commit
}
我想知道 appfuse 如何使用 session.beginTransaction() 和 session.getTransaction().commit() 来包装 dao 操作;
通过使用这种技术,程序员不必担心 hibernate 事务的问题。我希望它以这样一种方式,即使 dao 方法被重写,事务包装器代码也应该自动出现。 我尝试过将 dao 传递给装饰器类并将 dao 方法调用包装在装饰器类中。但是由于 dao 接口方法会发生变化,因此这个想法起作用了。我们究竟如何才能实现这一目标。
I was going through the hibernate tutorial and noticed that in every dao you have to get session,begin transaction.Perform all operations and then commit
private void createAndStoreEvent(String title, Date theDate) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
//Perform operations...
session.getTransaction().commit();
}
Then i have noticed in a framework called Appfuse which uses hibernate have dao methods as shown below.I dont see the begintransaction and commit
public List<Person> findByLastName(String lastName) {
//begintransaction
return getHibernateTemplate().find("from Person where lastName=?", lastName);
//Commit
}
I wonder how appfuse is wrapping up the dao operations with session.beginTransaction() and session.getTransaction().commit();
By using this technique the programmer doesn't have to bother about hibernate transaction stuff.I want it in such a a way that even if dao methods are overridden the transaction wrapper code should automatically come.
I have tried passing dao to a decorator class and wrapping the dao method call inside decorator class.But since the dao interface methods will change,the idea dint worked.How exactly we can achieve this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道 AppFuse 是如何做到这一点的,但是将事务管理引入应用程序的服务层的一种非常常见的方法是使用面向方面的编程。如果您使用的是 Spring 框架,这个 (来自手册)是一个很好的参考。
I don't know how AppFuse is doing it, but a very common way of introducing transaction management into the service layer of an application is by using Aspect Oriented Programming. If you're using the Spring Framework, this (from the manual) is a good reference.
< code>HibernateTemplate 是 Spring 的一部分。您可以通过此链接阅读更多相关信息。但从 Spring 3.0 开始,它被认为已被弃用,取而代之的是 声明式事务管理。
HibernateTemplate
is part of Spring. You can read more about it at this link. But starting with Spring 3.0, it's considered to be deprecated in favor of declarative transaction management.