Multiple Databases with Play Framework 2.1.x

女生的网名这么多〃 提交于 2019-12-29 21:10:57

问题


I have 2 databases that I need to connect to. I can easily connect to them in the application.conf file like so:

db.default.driver=org.postgresql.Driver
db.default.url="jdbc:postgresql://localhost/db1"
db.default.user=postgres
db.default.password="password"

db.secondary.driver=org.postgresql.Driver
db.secondary.url="jdbc:postgresql://localhost/db2"
db.secondary.user=postgres
db.secondary.password="password"

ebean.default="models.db1.*"
ebean.secondary="models.db2.*"

I have my model classes in those packages, and it DDL generates the tables properly.

The problem lies in actually working with these entities. Anything not in the "default" package throws this error (using the Users table in the secondary database as an example)

If I try to query all the rows of the table:

List<Users> users = Users.find.all();

It throws this error:

[PersistenceException: models.db2.Users is NOT an Entity Bean registered with this server?]

Even though I am 100% sure that the Users table is there in the backend, it is a registered table the DDL works and makes this table properly, and I am importing the proper classes.

Is there a certain way I need to query model classes that aren't in the default package?

EDIT: I realize that the stack trace shows that it's trying to use the DefaultServer. How can I make it use the secondary server?

    at com.avaje.ebeaninternal.server.core.DefaultServer.createQuery(DefaultServer.java:989) ~[avaje-ebeanorm-server.jar:na]
    at com.avaje.ebeaninternal.server.core.DefaultServer.createQuery(DefaultServer.java:946) ~[avaje-ebeanorm-server.jar:na]
    at com.avaje.ebeaninternal.server.core.DefaultServer.find(DefaultServer.java:982) ~[avaje-ebeanorm-server.jar:na]
    at play.db.ebean.Model$Finder.all(Model.java:254) ~[play-java-ebean_2.10.jar:2.1.3]

回答1:


Ok, your application.conf seems to be correct.

You may use the secondary server like this:

EbeanServer secondary = Ebean.getServer("secondary");
secondary.find(User.class).findList();

Once you've got your secondary server, you may treat it just as you treat the Ebean singleton.




回答2:


I had the same problem and I fixed it by specifying the server name at the Model.Finder level.

So in your case, in your User class, you should have something like :

public static Model.Finder<Long, User> find = new Finder<Long, User>("secondary", Long.class, User.class);



回答3:


You can use both:

public static Model.Finder<Long, User> find = new Finder<Long, User>("secondary", Long.class, User.class);

and

Ebean.getServer("secondary");

But you have to use the save method with the server declaration on your entity

public void save(String server)

Without save() ebean uses the default server, even on your user-entity!



来源:https://stackoverflow.com/questions/18305326/multiple-databases-with-play-framework-2-1-x

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