How do I create two EntityManager binding, one without any annotation and one with annotation?

124 views
Skip to first unread message

Kohei Nozaki

unread,
Jun 13, 2016, 6:11:42 AM6/13/16
to google-guice
Hello,

I want to create two EntityManager binding with guice-persist as follows:

1. Without any annotation
2. With an annotation (say, @SlaveDatabase)

So, I have created following module:

public class MyModule extends AbstractModule {

    @Override
    protected void configure() {
        install(new MasterPrivateModule());
        install(new SlavePrivateModule());
    }

    private static class MasterPrivateModule extends PrivateModule {
        @Override
        protected void configure() {
            install(new JpaPersistModule("masterPU"));

            expose(EntityManager.class);
        }
    }

    private static class SlavePrivateModule extends PrivateModule {
        @Override
        protected void configure() {
            install(new JpaPersistModule("slavePU"));

            final Provider<EntityManager> entityManagerProvider = binder().getProvider(EntityManager.class);
            bind(EntityManager.class).annotatedWith(SlaveDatabase.class).toProvider(entityManagerProvider);
            expose(EntityManager.class).annotatedWith(SlaveDatabase.class);
        }
    }
}

But it doesn't work. Guice produces following error:

com.google.inject.CreationException: Unable to create injector, see the following errors:

1) A binding to javax.persistence.EntityManager was already configured at mypkg.MyModule$MasterPrivateModule.configure(MyModule.java:25) (via modules: mypkg.MyModule -> mypkg.MyModule$MasterPrivateModule).
  at com.google.inject.persist.jpa.JpaPersistModule.configurePersistence(JpaPersistModule.java:69) (via modules: mypkg.MyModule -> mypkg.MyModule$SlavePrivateModule -> com.google.inject.persist.jpa.JpaPersistModule)
...

How do I write a module to achieve this requirement?

I have pushed a reproducer (testcase) and entire project to GitHub:

* Reproducer (testcase): 

Thanks.

Stephan Classen

unread,
Jun 13, 2016, 6:23:26 AM6/13/16
to google...@googlegroups.com
This is not possible. You need to define an notation for both entitymanagers.

Also have a look at onami-persist for enhanced multi pu support

Kohei Nozaki

unread,
Jun 19, 2016, 5:20:19 AM6/19/16
to google-guice
Hi Stephan,

Thanks for the info. eventually I created two annotated bindings for JPA classes. also I have blogged about it: http://www.nailedtothex.org/roller/kyle/entry/managing-multiple-jpa-persistence-units

Thanks,
Kohei

2016年6月13日月曜日 19時23分26秒 UTC+9 scl:
Reply all
Reply to author
Forward
0 new messages