Question

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

Was it helpful?

Solution

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top