Giter Club home page Giter Club logo

jpaenhancedbydynamicproxy's Introduction

JpaEnhancedByDynamicProxy

通过动态代理实现对Jpa的事务性增强

对 CustomerDao 进行事务的增强:

public class ProxyJpaTransactionMethod implements InvocationHandler {
    private CustomerDao customerDao;

    public ProxyJpaTransactionMethod(CustomerDao customerDao) {
        this.customerDao = customerDao;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        EntityTransaction tx = customerDao.getTransaction();
        Object result = null;
        try {
            System.out.println("开启事务");
            tx.begin();
            result = method.invoke(customerDao, args);
            System.out.println("提交事务");
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("回滚事务");
            tx.rollback();
        }
        return result;
    }
}

在调用时通过增强后的 CustomDao 进行调用:

public class CustomerDaoTest {

    private CustomerDao customerDao = new CustomerDaoImpl();

    {
        customerDao = (CustomerDao) Proxy.newProxyInstance(customerDao.getClass().getClassLoader(), customerDao.getClass().getInterfaces(), new ProxyJpaTransactionMethod(customerDao));
    }
    
    //...
}

jpaenhancedbydynamicproxy's People

Contributors

whl-1998 avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.