Hot questions for Using Neo4j in hibernate ogm

Top Java Programmings / Neo4j / hibernate ogm

Question:

I am trying to save an entity using Hibernate and Jersey.

The JSON that I try to send is:

{
"firstname":"Jon",
"middlename":"J",
"lastname":"Smith",
"dob":"10-10-1990",
"gender":"male"
}

When I send it with Postman, I get Status: 200 OK but the record is not saved in the database.

The database that I am using is Neo4j.

Here is my PersonDAO class:

package com.Neo4jRestAPI;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.hibernate.HibernateException;

import com.google.gson.Gson;

public class PersonDAO {

    public void addPerson(Person person){

        try {
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistence");
            EntityManager em = emf.createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();

            Person p = new Person();

            p.setFirstname(person.getFirstname());
            p.setMiddlename(person.getMiddlename());
            p.setLastname(person.getLastname());
            p.setDob(person.getDob());
            p.setGender(person.getGender());

            em.persist(p);
            em.flush();     
            tx.commit();
            em.clear(); 
            em.close(); 
            emf.close();
            }
        catch ( Exception e ) {
            e.printStackTrace();
        }
    }
}

This is how I try to send the data:

@POST
@Path("/person")
@Consumes("application/json")
public Response addPerson(Person person){

     person.setFirstname(person.getFirstname());
     person.setMiddlename(person.getMiddlename());
     person.setLastname(person.getLastname());
     person.setDob(person.getDob());
     person.setGender(person.getGender());

     PersonDAO dao = new PersonDAO();

     dao.addPerson(person);

     return Response.ok().build();
}

Does anyone know what I am doing wrong here?

EDIT

I was able to save an entity using native query but that way, the id is not automatically generated. I am still unable to save an entity with the way described above

When I remove the @GeneratedValue and specify the id in the JSON, then I am able to save the entity, so I assume the problem is there. I have tried several strategies but none of them worked.

This is how I try to auto-generate the id:

@Entity
@Table(name="Person")
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

Also, when I print the method getId(), I get the auto-incremented value.

Here is the Cypher query that has been executed:

"{"statements":[{"statement":"CREATE (n:ENTITY:Person {props}) RETURN n","parameters":{"props":{"firstname":"Jon","gender":"male","dob":"10-10-1990","middlename":"J","id":99,"lastname":"Smith"}},"includeStats":false,"resultDataContents":["graph"]}]}"

I am also getting a transaction rollback error but it does not say why it has been rolled back:

"Neo.ClientError.Transaction.TransactionNotFound","message":"Unrecognized transaction id. Transaction may have timed out and been rolled back

Here is my persistence.xml file

<?xml version="1.0"?>
<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="persistence">
    <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
    <properties>
        <property name="hibernate.ogm.datastore.provider" value="neo4j_http"/>
        <property name="hibernate.ogm.neo4j.database_path" value="C://path//to//database"/>
        <property name="hibernate.ogm.datastore.host" value="localhost:7474"/>
        <property name="hibernate.ogm.datastore.username" value="neo4j"/>
        <property name="hibernate.ogm.datastore.password" value="root"/>
    </properties>
  </persistence-unit>
  </persistence>

EDIT

This is the stack trace that I am getting:

log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. 

When I use log4j and add BasicConfiguratior.configure(), I get the following (it is quite big to post the whole log here, so I just posted a part of it where the error is thrown):

2342 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  >> "{"statements":[{"statement":"CREATE (n:ENTITY:Person {props}) RETURN n","parameters":{"props":{"firstname":"Anna","gender":"female","dob":"10-10-1990","middlename":"J","id":57,"lastname":"Smith"}},"includeStats":false,"resultDataContents":["graph"]}]}"
2345 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "HTTP/1.1 200 OK[\r][\n]"
2345 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "Date: Tue, 03 Oct 2017 09:01:10 GMT[\r][\n]"
2345 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "Content-Type: application/json[\r][\n]"
2345 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "Access-Control-Allow-Origin: *[\r][\n]"
2345 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "Content-Length: 372[\r][\n]"
2345 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "Server: Jetty(9.2.z-SNAPSHOT)[\r][\n]"
2345 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "[\r][\n]"
2345 [http-nio-8080-exec-4] DEBUG org.apache.http.impl.conn.DefaultClientConnection  - Receiving response: HTTP/1.1 200 OK
2345 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - << HTTP/1.1 200 OK
2345 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - << Date: Tue, 03 Oct 2017 09:01:10 GMT
2345 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - << Content-Type: application/json
2345 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - << Access-Control-Allow-Origin: *
2345 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - << Content-Length: 372
2345 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - << Server: Jetty(9.2.z-SNAPSHOT)
2345 [http-nio-8080-exec-4] DEBUG org.apache.http.impl.client.DefaultHttpClient  - Connection can be kept alive indefinitely
2346 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "{"commit":"http://localhost:7474/db/data/transaction/53/commit","results":[{"columns":["n"],"data":[{"graph":{"nodes":[{"id":"10","labels":["ENTITY","Person"],"properties":{"firstname":"Anna","gender":"female","dob":"10-10-1990","middlename":"J","id":57,"lastname":"Smith"}}],"relationships":[]}}]}],"transaction":{"expires":"Tue, 03 Oct 2017 09:02:10 +0000"},"errors":[]}"
2346 [http-nio-8080-exec-4] DEBUG org.apache.http.impl.conn.PoolingClientConnectionManager  - Connection [id: 1][route: {}->http://localhost:7474] can be kept alive indefinitely
2346 [http-nio-8080-exec-4] DEBUG org.apache.http.impl.conn.PoolingClientConnectionManager  - Connection released: [id: 1][route: {}->http://localhost:7474][total kept alive: 1; route allocated: 2 of 10; total allocated: 2 of 10]
2350 [http-nio-8080-exec-4] DEBUG org.hibernate.engine.transaction.internal.TransactionImpl  - committing
2350 [http-nio-8080-exec-4] DEBUG org.hibernate.event.internal.AbstractFlushingEventListener  - Processing flush-time cascades
2350 [http-nio-8080-exec-4] DEBUG org.hibernate.event.internal.AbstractFlushingEventListener  - Dirty checking collections
2350 [http-nio-8080-exec-4] DEBUG org.hibernate.event.internal.AbstractFlushingEventListener  - Flushed: 0 insertions, 0 updates, 0 deletions to 1 objects
2350 [http-nio-8080-exec-4] DEBUG org.hibernate.event.internal.AbstractFlushingEventListener  - Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
2350 [http-nio-8080-exec-4] DEBUG org.hibernate.internal.util.EntityPrinter  - Listing entities:
2350 [http-nio-8080-exec-4] DEBUG org.hibernate.internal.util.EntityPrinter  - com.Neo4jRestAPI.Person{firstname=Anna, gender=female, relationship_type=null, dob=10-10-1990, middlename=J, id=57, relationship=null, lastname=Smith}
2350 [http-nio-8080-exec-4] DEBUG org.apache.http.impl.conn.PoolingClientConnectionManager  - Connection request: [route: {}->http://localhost:7474][total kept alive: 1; route allocated: 2 of 10; total allocated: 2 of 10]
2350 [http-nio-8080-exec-4] DEBUG org.apache.http.impl.conn.PoolingClientConnectionManager  - Connection leased: [id: 1][route: {}->http://localhost:7474][total kept alive: 0; route allocated: 2 of 10; total allocated: 2 of 10]
2350 [http-nio-8080-exec-4] DEBUG org.apache.http.impl.client.DefaultHttpClient  - Stale connection check
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.client.protocol.RequestAddCookies  - CookieSpec selected: best-match
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.client.protocol.RequestAuthCache  - Auth cache not set in the context
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.client.protocol.RequestProxyAuthentication  - Proxy auth state: UNCHALLENGED
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.impl.client.DefaultHttpClient  - Attempt 1 to execute request
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.impl.conn.DefaultClientConnection  - Sending request: POST /db/data/transaction/54/commit HTTP/1.1
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  >> "POST /db/data/transaction/54/commit HTTP/1.1[\r][\n]"
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  >> "Accept: application/json[\r][\n]"
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  >> "Accept-Encoding: gzip, deflate[\r][\n]"
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  >> "Authorization: Basic bmVvNGo6Z2VuaXZpdHk=[\r][\n]"
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  >> "X-Stream: true[\r][\n]"
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  >> "Content-Length: 0[\r][\n]"
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  >> "Host: localhost:7474[\r][\n]"
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  >> "Connection: Keep-Alive[\r][\n]"
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  >> "[\r][\n]"
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - >> POST /db/data/transaction/54/commit HTTP/1.1
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - >> Accept: application/json
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - >> Accept-Encoding: gzip, deflate
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - >> Authorization: Basic bmVvNGo6Z2VuaXZpdHk=
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - >> X-Stream: true
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - >> Content-Length: 0
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - >> Host: localhost:7474
2352 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - >> Connection: Keep-Alive
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "HTTP/1.1 404 Not Found[\r][\n]"
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "Date: Tue, 03 Oct 2017 09:01:10 GMT[\r][\n]"
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "Content-Type: application/json[\r][\n]"
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "Access-Control-Allow-Origin: *[\r][\n]"
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "Content-Length: 178[\r][\n]"
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "Server: Jetty(9.2.z-SNAPSHOT)[\r][\n]"
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "[\r][\n]"
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.impl.conn.DefaultClientConnection  - Receiving response: HTTP/1.1 404 Not Found
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - << HTTP/1.1 404 Not Found
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - << Date: Tue, 03 Oct 2017 09:01:10 GMT
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - << Content-Type: application/json
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - << Access-Control-Allow-Origin: *
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - << Content-Length: 178
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.headers  - << Server: Jetty(9.2.z-SNAPSHOT)
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.impl.client.DefaultHttpClient  - Connection can be kept alive indefinitely
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.wire  -  << "{"results":[],"errors":[{"code":"Neo.ClientError.Transaction.TransactionNotFound","message":"Unrecognized transaction id. Transaction may have timed out and been rolled back."}]}"
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.impl.conn.PoolingClientConnectionManager  - Connection [id: 1][route: {}->http://localhost:7474] can be kept alive indefinitely
2354 [http-nio-8080-exec-4] DEBUG org.apache.http.impl.conn.PoolingClientConnectionManager  - Connection released: [id: 1][route: {}->http://localhost:7474][total kept alive: 1; route allocated: 2 of 10; total allocated: 2 of 10]
2355 [http-nio-8080-exec-4] DEBUG org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl  - Initiating JDBC connection release from afterTransaction
18718 [Finalizer] DEBUG org.apache.http.wire  -  << "{"password_change_required":false,"password_change":"http://localhost:7474/user/neo4j/password","username":"neo4j"}"
18719 [Finalizer] DEBUG org.apache.http.impl.conn.PoolingClientConnectionManager  - Connection [id: 0][route: {}->http://localhost:7474] can be kept alive indefinitely
18719 [Finalizer] DEBUG org.apache.http.impl.conn.PoolingClientConnectionManager  - Connection released: [id: 0][route: {}->http://localhost:7474][total kept alive: 2; route allocated: 2 of 10; total allocated: 2 of 10]

Also, another thing that I noticed is that when I send the JSON for the first time, I get the log like above after I send it for the second time, every line gets printed twice when I send it for the third time, every line gets printed 3 times, and so on...

I am not sure what is causing that but it might be the cause of the problem


Answer:

I was able to solve my problem by changing from tomcat 8.5 to wildfly 9. I am still not sure what was the problem with tomcat though, since all the other operations worked fine, just the insertion of people was causing problems.

Question:

I'm using Hibernate OGM with Neo4j database.

For every operation, like creating new entity, there are many log entries with Cypher queries produced:

...
2015-02-27 11:09:41.825+0000 INFO  [org.neo4j]: CREATE (n:ENTITY:TreeElement {id: {0}}) RETURN n
2015-02-27 11:09:41.869+0000 INFO  [org.neo4j]: CREATE (n:ENTITY:TreeElement {id: {0}}) RETURN n
2015-02-27 11:09:41.873+0000 INFO  [org.neo4j]: MATCH (n:ENTITY:TreeElement {id: {0}}) RETURN n
2015-02-27 11:09:41.908+0000 INFO  [org.neo4j]: MATCH (n:ENTITY:TreeElement {id: {0}}) RETURN n
2015-02-27 11:09:41.911+0000 INFO  [org.neo4j]: CREATE (n:ENTITY:TreeElement {id: {0}}) RETURN n
2015-02-27 11:09:41.913+0000 INFO  [org.neo4j]: MATCH (n:ENTITY:TreeElement {id: {0}}) RETURN n
2015-02-27 11:09:41.914+0000 INFO  [org.neo4j]: MATCH (n:ENTITY:TreeElement {id: {0}}) RETURN n
...

How to disable this?

I've tried setting hibernate.show_sql property in persistance.xml file:

   <property name = "hibernate.show_sql" value = "false" />

, but with no result.


Answer:

I don't think there is a way to disable it. I 've created https://hibernate.atlassian.net/browse/OGM-755 to keep track of the issue.

Question:

I am trying my hand on Neo4j + Hibernate OGM. I started with this tutorial. Starting from there I am now able to create and update entities, and also run some custom queries using JP-QL queries: 1, 2.

Using Neo4j Community Edition 3.1.0 for Windows 64 bit, selecting the data directory of my embedded database, and navigating to the web view, I am able to view the data successfully.

However, after that, I faced the following problems while running my Java application.

  1. When I tried to run the application, at the same time the Neo4j Community Edition server is also running, I faced the following problem:

    org.neo4j.kernel.StoreLockException: Store and its lock file has been locked by another process: target\test_data_dir\store_lock. Please ensure no other process is using this database, and that the directory is writable (required even for read-only access)

    This error seems to be quite self explanatory, which might be resolved by stopping the server. My question is, is there any tool/configuration, which let me do both at the same time; i.e. run the application, and view the data in server.

  2. Another major error that I faced after stopping the server and running the application again, is the below one.

    org.neo4j.kernel.impl.storemigration.StoreUpgrader$UnexpectedUpgradingStoreVersionException: 'G:\Workspace\Java\Neo4jTest\target\test_data_dir\neostore.nodestore.db' has a store version number that we cannot upgrade from. Expected 'v0.A.3' but file is version '

    If I delete the database and start application (from scratch) again, then everything is okay till I start the server. How this can be resolved?

Additional Info:

  • My Maven dependencies:

    <dependencies>
    
        <!-- https://mvnrepository.com/artifact/org.hibernate.ogm/hibernate-ogm-neo4j -->
        <dependency>
            <groupId>org.hibernate.ogm</groupId>
            <artifactId>hibernate-ogm-neo4j</artifactId>
            <version>5.0.4.Final</version>
        </dependency>
    
        <!-- https://mvnrepository.com/artifact/org.jboss.jbossts/jbossjta -->
        <dependency>
            <groupId>org.jboss.jbossts</groupId>
            <artifactId>jbossjta</artifactId>
            <version>4.16.6.Final</version>
        </dependency>
    
    </dependencies>
    
  • My persitence.xml:

    <?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="hikePu" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
    
        <properties>
            <property name="hibernate.ogm.datastore.provider" value="neo4j_embedded" />
            <property name="hibernate.ogm.datastore.database" value="HikeDB" />
            <property name="hibernate.ogm.neo4j.database_path" value="target/test_data_dir" />
            <property name="hibernate.ogm.neo4j.configuration_resource_name" value="target/test_data_dir/_myNeo4j.conf" />
        </properties>
    </persistence-unit>
    

  • _myNeo4j.conf:

    #***************************************************************
    # Server configuration
    #***************************************************************
    
    # This setting constrains all `LOAD CSV` import files to be under the `import` directory. Remove or uncomment it to
    # allow files to be loaded from anywhere in filesystem; this introduces possible security problems. See the `LOAD CSV`
    # section of the manual for details.
    dbms.directories.import=import
    
    # Require (or disable the requirement of) auth to access Neo4j
    dbms.security.auth_enabled=true
    
    # With default configuration Neo4j only accepts local connections.
    # To accept non-local connections, uncomment this line:
    #dbms.connectors.default_listen_address=0.0.0.0
    
    # You can also choose a specific network interface, and configure a non-default
    # port for each connector, by setting their individual listen_address.
    
    # The address at which this server can be reached by its clients. This may be the server's IP address or DNS name, or
    # it may be the address of a reverse proxy which sits in front of the server. This setting may be overridden for
    # individual connectors below.
    #dbms.connectors.default_advertised_address=localhost
    
    # You can also choose a specific advertised hostname or IP address, and
    # configure an advertised port for each connector, by setting their
    # individual advertised_address.
    
    # Bolt connector
    dbms.connector.bolt.enabled=true
    #dbms.connector.bolt.tls_level=OPTIONAL
    #dbms.connector.bolt.listen_address=:7687
    
    # HTTP Connector
    dbms.connector.http.enabled=true
    #dbms.connector.http.listen_address=:#{default.http.port}
    
    # HTTPS Connector
    dbms.connector.https.enabled=true
    #dbms.connector.https.listen_address=:#{default.https.port}
    
    # Certificates directory
    # dbms.directories.certificates=certificates
    
    #*****************************************************************
    # Administration client configuration
    #*****************************************************************
    
    
    # Comma separated list of JAX-RS packages containing JAX-RS resources, one
    # package name for each mountpoint. The listed package names will be loaded
    # under the mountpoints specified. Uncomment this line to mount the
    # org.neo4j.examples.server.unmanaged.HelloWorldResource.java from
    # neo4j-examples under /examples/unmanaged, resulting in a final URL of
    # http://localhost:${default.http.port}/examples/unmanaged/helloworld/{nodeId}
    #dbms.unmanaged_extension_classes=org.neo4j.examples.server.unmanaged=/examples/unmanaged
    
    #*****************************************************************
    # HTTP logging configuration
    #*****************************************************************
    
    # HTTP logging is disabled. HTTP logging can be enabled by setting this
    # property to 'true'.
    dbms.logs.http.enabled=false
    
    # Enable this to be able to upgrade a store from an older version.
    dbms.allow_format_migration=true
    
    # The amount of memory to use for mapping the store files, in bytes (or
    # kilobytes with the 'k' suffix, megabytes with 'm' and gigabytes with 'g').
    # If Neo4j is running on a dedicated server, then it is generally recommended
    # to leave about 2-4 gigabytes for the operating system, give the JVM enough
    # heap to hold all your transaction state and query context, and then leave the
    # rest for the page cache.
    # The default page cache memory assumes the machine is dedicated to running
    # Neo4j, and is heuristically set to 50% of RAM minus the max Java heap size.
    #dbms.memory.pagecache.size=10g
    
    # Enable this to specify a parser other than the default one.
    #cypher.default_language_version=2.0
    
    # Keep logical logs, helps debugging but uses more disk space, enabled for
    # legacy reasons To limit space needed to store historical logs use values such
    # as: "7 days" or "100M size" instead of "true".
    #dbms.tx_log.rotation.retention_policy=7 days
    
    # Enable shell server so that remote clients can connect via Neo4j shell.
    #dbms.shell.enabled=true
    # The network interface IP the shell will listen on (use 0.0.0.0 for all interfaces).
    #dbms.shell.host=127.0.0.1
    # The port the shell will listen on, default is 1337.
    #dbms.shell.port=1337
    
    allow_store_upgrade=true
    

Answer:

only one process at the time can acquire a lock on the embedded Neo4j.

Therefore, if you are using OGM you cannot access it using the Neo4j server, or vicecersa. I don't think there is any way to solve this issue at the moment.

If you want to check the DB while the application is running you need to connect to the server using the Bolt protocol or the HTTP API. You just need to update the Hibernate OGM configuration file.

Hibernate OGM 5.0.4.Final is using an older version of Neo4j: 2.3.5 When you open and close the server the file version change and Hibernate OGM cannot recognize it anymore.

Hibernate OGM 5.1.0.Beta3 is using Neo4j 3.0.8 at the moment, but I opened an issue to upgrade it.

Question:

I would like to retrieve entity properties in a format like this: property_name: value.

I am trying to get the result this way:

public void retrievePerson(){
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistence");
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
      try{

         String query = "MATCH (p:Person {id:3}) RETURN p.firstname, p.lastname";

         List<Object[]> person = (List<Object[]>) em.createNativeQuery(query).getResultList();

         em.flush();
         tx.commit();
         em.clear();
         em.close();
         emf.close();

      }
      catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }
   }

I read somewhere the the object returned by the query is a managed entity.

I would like the result to be like this: {"firstname":"Jon", "lastname":"Smith"}

I have found this setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE which might be something that I am looking for but I am unable to get it to work.

Is there a way to achieve this?


Answer:

Try changing your query to:

MATCH (p:Person {id:3})
RETURN { firstname: p.firstname, lastname: p.lastname }

Question:

I am trying to use Hibernate to store family tree information. From what I have seen in the documentation, in order to connect two or more entities, they have to be from different classes. So, in order to create relationships between husband and wife, I would need to have two classes respectively. I think this is pointless because both classes would be identical (keep in mind that the tree can be quite large so I would have a lot of duplicate classes that way).

Is there a way to have a single class, for example Person and do the connections just from that class?

Also, if there is not way to achieve that, how would I connect siblings, for example

(p:Sibling)-[:SIBLING_OF]->(k:Sibling)

when they will both be from same class Sibling?


Answer:

You can create relationships with entities of the same class the same way you create relationships with entities of different classes.

You can find an example of the mapping on the Hibernate OGM project sources: https://github.com/hibernate/hibernate-ogm/blob/5.2.0.Alpha1/core/src/test/java/org/hibernate/ogm/backendtck/associations/recursive/TreeNode.java

and the realtive testcase: https://github.com/hibernate/hibernate-ogm/blob/5.2.0.Alpha1/core/src/test/java/org/hibernate/ogm/backendtck/associations/recursive/RecursiveAssociationsTest.java

The tests map a tree structure with nodes having a parent node and many children, the mapping of the entity looks like like this:

@Entity
public class TreeNode {

    @Id
    private String name;

    @ManyToOne
    private TreeNode parent;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent",
        cascade = CascadeType.ALL, orphanRemoval = true)
    private List<TreeNode> children = new ArrayList<TreeNode>( 3 );

    ...
}

NOTE: Based on your needs, you can create the association using native queries but I wouldn't recommend it. Hibernate OGM becomes unaware of the relationship and problems might occur.