Hibernate Rest状态代码:200但实体未保存

时间:2017-09-27 12:48:04

标签: java hibernate neo4j hibernate-ogm

我正在尝试使用Hibernate和Jersey保存实体。

我尝试发送的JSON是:

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

当我使用Postman发送时,我得到Status: 200 OK,但记录未保存在数据库中。

我使用的数据库是Neo4j。

这是我的PersonDAO课程:

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();
        }
    }
}

这是我尝试发送数据的方式:

@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();
}

有谁知道我在这里做错了什么?

修改

我能够使用native query保存实体,但这样,id不会自动生成。我仍然无法按照上述方式保存实体

当我删除@GeneratedValue并在JSON中指定id时,我能够保存实体,因此我认为存在问题。我尝试了几种策略,但没有一种能有效。

这是我尝试自动生成id

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

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

此外,当我打印方法getId()时,我得到自动递增的值。

以下是已执行的Cypher查询:

"{"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"]}]}"

我也收到了一个事务回滚错误,但它没有说明为什么它已被回滚:

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

这是我的persistence.xml文件

<?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>

修改

这是我得到的堆栈跟踪:

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. 

当我使用log4j并添加BasicConfiguratior.configure()时,我得到以下内容(在此处发布整个日志非常大,所以我只是发布了错误的部分内容):

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]

另外,我注意到的另一件事是,当我第一次发送JSON时,我在第二次发送之后得到上面的日志,当我第三次发送它时,每行都被打印两次,每行打印3次,依此类推......

我不确定是什么造成了这种情况,但可能是导致问题的原因

4 个答案:

答案 0 :(得分:2)

我可以通过从tomcat 8.5更改为wildfly 9来解决我的问题。我仍然不确定tomcat的问题是什么,因为所有其他操作都运行正常,只是插入人员导致了问题。

答案 1 :(得分:0)

我认为,问题是

@GeneratedValue(strategy = GenerationType.AUTO)

无法找到创建密钥的适当方法。 我建议尝试这样的事情:

@SequenceGenerator(name = "sequence_generator_name", sequenceName = "sequence_name", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence_generator_name")

使用数据库序列创建密钥。如果您不使用架构自动更新,则必须手动创建序列。语法细节取决于您的数据库。

答案 2 :(得分:0)

我想我发现了错误,改变了这些行:

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

通过这些方式:

em.persist(p);
em.flush();
em.close();
tx.commit();
emf.close();

答案 3 :(得分:0)

替换它:

catch ( Exception e ) {
    e.printStackTrace();
}

用这个:

catch ( Exception e ) {
    throw new RuntimeException(e);
}

异常不会被重新抛出,所以就你的REST层而言,PersonDAO.addPerson是成功的,它会产生一个OK响应。