Configuration of two Mongo databases


I want to configure two mongo databases. how can I define it in the Persistence.xml file?

You need to create two distinct persistence units for this case:

<persistence ...>
    <persistence-unit name="mongoPU-1" transaction-type="JTA">
    <persistence-unit name="mongoPU-2" transaction-type="JTA">

Then in your code you can access the one you need with the annotation:

EntityManagerFactory ef;


EntityManagerFactory emf = Persistence.createEntityManagerFactory( "mongoPU-1 );

Note that they are two distinct persistence units and you cannot, for example, have a join on two entities that are not in the same factory.

I hope this help.

thank you for your quick response. this works perfectly in my project but now i have another issue in my project i have a some object variables, when i want to perform a query it gives me the error that type is wrong.

private object environment;
private object extension;

unders these object i also some nested object, should i have to perform this query in native language or i can also use JPQL?

Hibernat OGM doesn’t know how to convert the object and that’s why you see an error.
Supported built-in type are here:

You could use a native query but a better solution would be to change the mapping of your entities using the appropriate type. If the document are nested you can map them as embedded entities:

One example from the documentation:

public class News {

    private String id;
    private String title;

    private NewsPaper paper;

    // getters, setters ...

public class NewsPaper {

    private String name;
    private String owner;

    // getters, setters ...

i have a one more question, is this modle also work with SQL or it is only for NoSQL databases?

Yes, that’s the idea around Hibernate OGM.

If you use the JPA annotations and JPQL it doesn’t matter which datastore you are using (in theory).

Moving from a nosql datastore to a relational one, should work fine.

1 Like

Thank you very much for your help.