简体   繁体   中英

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

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 aa 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.

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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