【问题标题】:Play framework 2 + JPA with multiple persistenceUnitPlay framework 2 + JPA with multiple persistenceUnit
【发布时间】:2013-05-17 14:43:47
【问题描述】:

我正在努力使用 Play 和 JPA,以便能够使用与两个不同持久性单元相关联的两个不同 javax.persistence.Entity 模型(需要能够连接到不同的数据库 - 例如 Oracle 和 MySQL分贝)。

问题来自始终绑定到默认 JPA persitenceUnit 的事务(请参阅 jpa.default 选项)。

这里有两个控制器动作,显示了我找到的手动定义持久性的解决方案: 包控制器;

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();
    }
}

这个解决方案似乎并不真正“干净”。我想知道您是否知道一种更好的方法来避免需要手动修改所使用的事务。

为此,我在 git 上创建了一个带有工作示例应用程序的存储库,该示例应用程序显示了我如何配置项目。

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

感谢您的帮助

【问题讨论】:

    标签: jpa playframework-2.0 persistence.xml


    【解决方案1】:

    我也遇到了同样的问题。太多的建议是关于PersistenceUnit 注释或getJPAConfig。但它们似乎都不适用于游戏框架。
    我发现了一种在我的项目中效果很好的方法。也许你可以试试。
    playframework2 how to open multi-datasource configuration with jpa
    哎呀!

    【讨论】:

    • 你说得对,我也找到了使用 JPA.em("dbSource") 的解决方案。然而,解决方案并不完美。默认的 Play JPA Helper 实现不提供同时打开多个 entityManager 的可能性。我必须添加一些棘手的代码才能切换 entityManager 的来源。
    猜你喜欢
    • 2016-03-09
    • 2015-10-08
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多