Configuration of two Mongo databases

Hi,

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">
        <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
        <properties>
            ...
        </properties>
    </persistence-unit>
    <persistence-unit name="mongoPU-2" transaction-type="JTA">
        <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>        
        <properties>
            ...
        </properties>
    </persistence-unit>
</persistence>

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

@PersistenceUnit(uniteName="mongoPU-2")
EntityManagerFactory ef;

or

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.

e.g
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: https://docs.jboss.org/hibernate/stable/ogm/reference/en-US/html_single/#mongodb-built-in-types

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: https://docs.jboss.org/hibernate/stable/ogm/reference/en-US/html_single/#_embedded_objects_and_collections_2

One example from the documentation:



@Entity
public class News {

    @Id
    private String id;
    private String title;

    @Embedded
    private NewsPaper paper;

    // getters, setters ...
}

@Embeddable
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.