简体   繁体   English

不同 dao 方法的相同代码包装

[英]Same Code wrapping for different dao methods

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我正在阅读 hibernate 教程,并注意到在每个 dao 中你必须得到 session,开始事务。执行所有操作,然后提交

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然后我注意到在一个名为 Appfuse 的框架中使用 hibernate 有如下所示的 dao 方法。我没有看到 begintransaction 和 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();我想知道 appfuse 是如何使用 session.beginTransaction() 和 session.getTransaction().commit() 来完成 dao 操作的。

By using this technique the programmer doesn't have to bother about hibernate transaction stuff.I want it in such aa way that even if dao methods are overridden the transaction wrapper code should automatically come.通过使用这种技术,程序员不必担心 hibernate 事务的东西。我希望它以这样一种方式实现,即使 dao 方法被覆盖,事务包装器代码也应该自动出现。 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.我已经尝试将 dao 传递给装饰器 class 并将 dao 方法调用包装在装饰器 class 中。但是由于 dao 接口方法会改变,所以这个想法很有效。我们如何才能实现这一点。

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.我不知道 AppFuse 是如何做到的,但是将事务管理引入应用程序的服务层的一种非常常见的方法是使用面向方面的编程。 If you're using the Spring Framework, this (from the manual) is a good reference.如果您使用的是 Spring 框架,(来自手册)是一个很好的参考。

HibernateTemplate is part of Spring. HibernateTemplate是 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 .但是从 Spring 3.0 开始,它被认为已被弃用,有利于声明式事务管理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM