Hibernate ogm infinispan @manytoone двунаправленная проблема на wildfly 17 - PullRequest
0 голосов
/ 28 января 2020

У меня возникает проблема, когда я использую infinispan ogm с конфигурацией хранилища файлов. Моя проблема заключается в следующем. Я установил на wildfly 17 очень маленькое REST-приложение, способное сохранять и читать очень простую модель данных. Модель данных состоит из двунаправленной многофакторной ассоциации.

@Entity
public class Foo {
    @Id
    private String id;

    private String name;

    @OneToMany(cascade = CascadeType.ALL , orphanRemoval = true, mappedBy = "foo")
    private List<Bar> bars = new ArrayList<>();

    public void addBar(String name) {
        Bar bar = new Bar();
        bar.setName("Bar_"+name);
        String id_foo = "Foo_" + name + "_id";
        String id_bar = "Bar_" + id_foo;
        bar.setId(id_bar);
        bars.add(bar);
        bar.setFoo(this);

   //getter and setter
}
@Entity(name = "Bar")
public class Bar {

    @Id
    private String id;

    private String name;

    @ManyToOne
    private Foo foo;

    }

}

public class FooBarService {

    @Inject
    protected EntityManager entityManager;

    @Transactional
    String persisitFoo(String name) {


        Foo foo = new Foo();
        String id_foo = "Foo_" + name + "_id";
        foo.setId(id_foo);
        foo.setName("Foo_"+name);

        //add a bar
        foo.addBar(name);

        entityManager.persist(foo);
        entityManager.flush();

        Foo result = entityManager.find(Foo.class, id_foo);
        return result.toString();
    }

    @Transactional
    String getBar(String name) {

        String id_foo = "Foo_" + name + "_id";
        String id_bar = "Bar_" + id_foo;

        // build the EntityManagerFactory as you would build in in Hibernate ORM

        Bar result = entityManager.find(Bar.class, id_bar);
        entityManager.flush();

        return result.toString();
    }

    @Transactional
    String getFoo(String name) {


        String id_foo = "Foo_" + name + "_id";

        // build the EntityManagerFactory as you would build in in Hibernate ORM

        Foo result = entityManager.find(Foo.class, id_foo);
        entityManager.flush();

        return result.toString();
    }


Когда я сохраняю Foo (состоящий из одного Bar), я могу получить getFoo, а объект Foo содержит Bar, но когда я перезапускаю остальное приложение , когда я получаю объект Foo, я теряю Bar Assocation . Когда я получаю объект Bar, ассоциация с объектом Foo присутствует. Вот конфигурация моего приложения presistence.properties (я использую производителя для программной сборки entityManager на основе HibernateOgmPersistence). Похоже, что двунаправленный работает только в одном направлении

####################################################################
# Configure hibernate OGM based on infinispan provider
####################################################################
hibernate.ogm.datastore.provider=infinispan_embedded

#############################################
#  CACHE_PER_KIND: Three caches will be used: 
#  1) one cache for all entities
#  2) one cache for all associations 
#  3) one cache for all id sources
##############################################
hibernate.ogm.datastore.keyvalue.cache_mapping=CACHE_PER_KIND
########################################################################
# Should point to the resource name of an Infinispan configuration file.
# The referenced Infinispan configuration should define a CacheStore
# for entities, associations adn id sources 
#########################################################################
hibernate.ogm.infinispan.configuration_resource_name=ems-model-infinispan.xml

здесь есть бесконечная конфигурация

<?xml version="1.0" encoding="UTF-8"?>
<!--
 ~ Hibernate OGM, Domain model persistence for NoSQL datastores
 ~
 ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later
 ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<infinispan
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="urn:infinispan:config:9.4 http://infinispan.org/schemas/infinispan-config-9.4.xsd"
        xmlns="urn:infinispan:config:9.4">


    <jgroups>
        <!-- This is the default JGroups stack -->
         <stack-file name="ems-jgroups" path="ems-jgroups-udp.xml"/>
    </jgroups>

    <cache-container name="ems-model" default-cache="DEFAULT" statistics="false" shutdown-hook="DONT_REGISTER">

        <transport stack="ems-jgroups"  cluster="EMS"/>
        <jmx duplicate-domains="true"/>

        <!-- ***************************************************************** -->
        <!--     Default cache (no longer used as template, since infinispan 9 -->
        <!-- ***************************************************************** -->
        <replicated-cache name="DEFAULT" mode="SYNC" statistics="false" statistics-available="false">
            <locking isolation="REPEATABLE_READ"/>
            <!--  transaction mode="BATCH" locking="PESSIMISTIC" transaction-manager-lookup="org.infinispan.transaction.lookup.WildflyTransactionManagerLookup"/ -->
            <transaction mode="BATCH" locking="PESSIMISTIC"/>
            <expiration interval="-1"/>
            <persistence>
                <file-store fetch-state="true" preload="true" path="/root/infinispan"/>
            </persistence>
            <state-transfer timeout="480000"/>
        </replicated-cache>

        <!-- *************************************** -->
        <!--     Cache to store the OGM entities     -->
        <!-- *************************************** -->
        <replicated-cache name="ENTITIES" mode="SYNC" statistics="false" statistics-available="false">
            <locking isolation="REPEATABLE_READ"/>
            <transaction mode="BATCH" locking="PESSIMISTIC"/>
            <expiration interval="-1"/>
            <persistence>
                <file-store fetch-state="true" preload="true" path="/root/infinispan"/>
            </persistence>
            <state-transfer timeout="480000"/>
        </replicated-cache>

        <!-- *********************************************** -->
        <!--   Cache to store the relations across entities  -->
        <!-- *********************************************** -->
        <replicated-cache name="ASSOCIATIONS" mode="SYNC" statistics="false" statistics-available="false">
            <locking isolation="REPEATABLE_READ"/>
            <transaction mode="BATCH" locking="PESSIMISTIC"/>
            <expiration interval="-1"/>
            <persistence>
                <file-store fetch-state="true" preload="true" path="/root/infinispan"/>
            </persistence>
            <state-transfer timeout="480000"/>
        </replicated-cache>

        <!-- ***************************** -->
        <!--   Cache to store identifiers  -->
        <!-- ***************************** -->
        <replicated-cache name="IDENTIFIERS" mode="SYNC" statistics="false" statistics-available="false">
            <locking isolation="REPEATABLE_READ"/>
            <transaction mode="BATCH" locking="PESSIMISTIC"/>
            <expiration interval="-1"/>
            <persistence>
                <file-store fetch-state="true" preload="true" path="/root/infinispan"/>
            </persistence>
            <state-transfer timeout="480000"/>
        </replicated-cache>

    </cache-container>
</infinispan>

используемая версия hibernate ogm равна

<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.hibernate.ogm</groupId>
                <artifactId>hibernate-ogm-bom</artifactId>
                <version>5.4.1.Final</version> 
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

Обратите внимание, что Я изменил провайдера с помощью mongodb, и он отлично работал.

hibernate.ogm.datastore.provider=mongodb
hibernate.ogm.datastore.host:127.0.0.1:27017
hibernate.ogm.datastore.database:ems
hibernate.ogm.datastore.create_database:true
...