Play framework 2 + JPA with multiple persistenceUnit

不想你离开。 提交于 2019-12-08 13:04:06

问题


I'm struggling with Play and JPA in order to be able to use two different javax.persistence.Entity model associated to two different persistence units (needed to be able to connect to different DB - for example an Oracle and a MySQL db).

The problem come from the Transaction which is always bind to the default JPA persitenceUnit (see jpa.default option).

Here is two controller actions which show the solution I found to manually define the persistence : package controllers;

import models.Company;
import models.User;
import play.db.jpa.JPA;
import play.db.jpa.Transactional;
import play.mvc.Controller;
import play.mvc.Result;

public class Application extends Controller {
    //This method run with the otherPersistenceUnit
    @Transactional(value="other")
    public static Result test1() {
        JPA.em().persist(new Company("MyCompany"));

        //Transaction is run with the "defaultPersistenceUnit"
        JPA.withTransaction(new play.libs.F.Callback0() {
            @Override
            public void invoke() throws Throwable {
                JPA.em().persist(new User("Bobby"));
            }
        }); 
        return ok();
    }


    //This action run with the otherPersistenceUnit
    @Transactional
    public static Result test2() {
        JPA.em().persist(new User("Ryan"));

        try {
            JPA.withTransaction("other", false, new play.libs.F.Function0<Void>() {
                public Void apply() throws Throwable {
                    JPA.em().persist(new Company("YourCompany"));
                    return null;
                }
            });
        } catch (Throwable throwable) {
            throw new RuntimeException(throwable);
        }
        return ok();
    }
}

This solution doesn't seem to be really "clean". I'd like to know if you know a better way to avoid the need to manually modify the transaction used.

For this purpose, I created a repo on git with a working sample application which shows how I configured the project.

https://github.com/cm0s/play2-jpa-multiple-persistenceunit

Thank you for your help


回答1:


i met the same problem, too. too many advices are about PersistenceUnit annotation or getJPAConfig. but both them seem not work in play framework.
i found out a method which works well in my projects. maybe you can try it.
playframework2 how to open multi-datasource configuration with jpa
gud luk!



来源:https://stackoverflow.com/questions/16611839/play-framework-2-jpa-with-multiple-persistenceunit

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