Play2 How to manage the transaction from the service layer instead of action layer?

坚强是说给别人听的谎言 提交于 2019-12-30 13:59:26

问题


I am using Play2.1.1 Java with JPA2.0 with hibernate implementation.

to control the transaction by code instead of using @transactional like below is the normal JPA code style, Is there any way to work like below at Play? or how to use JPA.withtranaction() to do? I tried it, no idea how to pass in the parameter, I am not familiar with functional code. thanks a lot. Please give me some sample code based on below.

public  void createActorB(final String email, final String psw) throws Throwable {
    EntityManager manager = JPA.em();
    try {
        EntityTransaction ex = manager.getTransaction();
        this.dbActor.setEmail(email);
        this.dbActor.setCredential(psw);
        manager.persist(this.dbActor);
        ex.commit();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new ActorException(CODE.UNKNOWN, e);
    } finally {
        manager.close();
    }
}

Now I change my code below to start transaction from service layer, It does not looks efficient, is there any other way to write? thanks

private void internalCreateActor(String email, String psw) throws ActorException {
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(psw))
            throw new ActorException(CODE.INVALIDE_PARAMETER);
        try {
            this.dbActor.setEmail(email);
            this.dbActor.setCredential(psw);
            this.dbActor.setCreateD(new Date());
            JPA.em().persist(this.dbActor);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new ActorException(CODE.UNKNOWN, e);
        }
    }

 public void createActor(final String email, final String psw, final String cellPhone, final Actor.TYPE type)
            throws Throwable {

        JPA.withTransaction(new Callback0() {
            @Override
            public void invoke() throws Throwable {
                internalCreateActor(email, psw, cellPhone, type);
            }
        });
    }

回答1:


something like this:

public static User getUserByIdentity(final AuthUserIdentity identity) {
    try {
        return JPA.withTransaction(new play.libs.F.Function0<User>() {
            public User apply() {       
                return User.findByAuthUserIdentity(identity);
            }
        });
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }       
}



回答2:


After some time research, I write a method JPAUtil referring to JPA provided by Play which can use normally to control the transaction manually from the service layer actually everywhere.

public class JPAUtil {

    static ThreadLocal<EntityManager> currentEntityManager = new ThreadLocal<EntityManager>();

    /**
     * Get the EntityManager for specified persistence unit for this thread.
     */
    public static EntityManager em(String key) {
        Application app = Play.application();
        if (app == null) {
            throw new RuntimeException("No application running");
        }

        JPAPlugin jpaPlugin = app.plugin(JPAPlugin.class);
        if (jpaPlugin == null) {
            throw new RuntimeException("No JPA EntityManagerFactory configured for name [" + key + "]");
        }

        EntityManager em = jpaPlugin.em(key);
        if (em == null) {
            throw new RuntimeException("No JPA EntityManagerFactory configured for name [" + key + "]");
        }

        bindForCurrentThread(em);

        return em;
    }

    /**
     * Get the default EntityManager for this thread.
     */
    public static EntityManager em() {
        EntityManager em = currentEntityManager.get();
        if (em == null) {
            return em(Constants.DATASOURCEKEY);
        }
        return em;
    }

    /**
     * Bind an EntityManager to the current thread.
     */
    public static void bindForCurrentThread(EntityManager em) {
        currentEntityManager.set(em);
    }

    public static void closeEM() {
        EntityManager em = currentEntityManager.get();
        if (em != null) {
            em.close();
        }
        bindForCurrentThread(null);
    }

    public static void beginTransaction() {
        em().getTransaction().begin();
    }

    public static void commitTransaction() {
        em().getTransaction().commit();
    }

}


来源:https://stackoverflow.com/questions/18545907/play2-how-to-manage-the-transaction-from-the-service-layer-instead-of-action-lay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!