Search code examples
javamongodbhibernatejpahibernate-ogm

Hibernate configuration with MongoDB


I've been trying to mess around with MongoDB and Hibernate in Java. I'm having some troubles with the configuration file for it.

I've already used Hibernate in the past with SQL DB, but it seems that the config file has to be quite different for MongoDB.

According to this documentation, it should looks something like this:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">

    <persistence-unit name="eshop" transaction-type="JTA">
        <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
        <class>org.hsnr.rest.domain.entities.Address</class>
        <class>org.hsnr.rest.domain.entities.Order</class>
        <class>org.hsnr.rest.domain.entities.Person</class>
        <class>org.hsnr.rest.domain.entities.Product</class>
        <class>org.hsnr.rest.domain.entities.User</class>
        <properties>
            <property name="hibernate.transaction.jta.platform"
                            value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform" />
            <property name="hibernate.ogm.datastore.provider"
                            value="mongodb" />
        </properties>
    </persistence-unit>
</persistence>

However, when I try to create a session with

new Configuration().configure().buildSessionFactory();

I get a following error:

org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 5 and column 28 in RESOURCE hibernate.cfg.xml. Message: cvc-elt.1: Cannot find the declaration of element 'persistence'.

Is my aproach wrong or is there something I overlooked?


Solution

  • You can try basic test set up like below for your config.

    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory( "eshop" );
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();
    // perform operations here
    entityManager.getTransaction().commit();
    entityManager.close();
    entityManagerFactory.close();