当前位置: 首页 > 知识库问答 >
问题:

使用Spring Boot和Neo4j通过REST API插入实体时出错

时经纬
2023-03-14

我正在用Spring Boot测试Neo4j,当我试图使用Rest API插入元素时,我发现了以下问题,我得到了JSON不能序列化到实体的错误。如果有人能帮助我或解释如何更改我的代码或如何序列化该实体,我将不胜感激。我的课是...用户实体

@NodeEntity
public class User extends AbstractEntity{

    @Id
    @GeneratedValue
    private Long id;

    private String firstname, lastname;


    @NotNull @NotBlank @Email
    @Index(unique = true)
    private String email;

    @Index(unique = true)
    private String phone;

    @Relationship(type = "ADDRESS")
    private Set<Address> addresses = new HashSet<>();

    public User() {
    }
    //get & set & const....
    }

Adrress实体

@NodeEntity
public class Address extends AbstractEntity{
    /*Update the OMG [https://neo4j.com/developer/neo4j-ogm] and remove de id.
     Keep the id in AbstractEntity*/
    @Id
    @GeneratedValue
    private Long id;

    private String street, city;

    @Relationship(type = "COUNTRY")
    private Country country;

    public Address(String street, String city, Country country) {
        this.street = street;
        this.city = city;
        this.country = country;
    }

    public Address() {
    }
    //get & set & const...
    }

国家实体

@NodeEntity
public class Country extends AbstractEntity {
    /*Update the OMG [https://neo4j.com/developer/neo4j-ogm] and remove de id.
     Keep the id in AbstractEntity*/
    @Id
    @GeneratedValue
    private Long id;

    @Index(unique=true)
    private String code;

    private String name;

    public Country(String code, String name) {
        this.code = code;
        this.name = name;
    }

    public Country() {
    } 
  }

抽象实体

@EnableNeo4jAuditing
public abstract class AbstractEntity {

    public abstract Long getId();

    @Transient
    private SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");

    private Date created = new Date();

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    @Override
    public boolean equals(Object obj) {

        if (this == obj) {
            return true;
        }

        if (getId() == null || obj == null || !getClass().equals(obj.getClass())) {
            return false;
        }
        return getId().equals(((AbstractEntity) obj).getId());

    }

    @Override
    public int hashCode() {
        return getId() == null ? 0 : getId().hashCode();
    }
}

面向商店用户的简单存储库类

public interface UserRepository extends Neo4jRepository<User, Long> {

    User findByFirstname(String name);

    @Override
    void delete(User deleted);
}

我的服务课

@Service
public class UserService {
     private UserRepository userRepository;
    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    public Iterable<User> contact() {
        return userRepository.findAll();
    }
    public User save(User user) {
            userRepository.save(user);
            return user;
    }
    public User show(Long id) {
        return userRepository.findById(id).get();
    }
    public User update(Long id, User user) {
        User c = userRepository.findById(id).get();
        if(user.getFirstname()!=null && !user.getFirstname().trim().isEmpty())
            c.setFirstname(user.getFirstname().trim());
        if(user.getLastname()!=null && !user.getLastname().trim().isEmpty())
            c.setLastname(user.getLastname().trim());
        if(user.getEmail()!=null && !user.getEmail().trim().isEmpty())
            c.setEmail(user.getEmail().trim());
        userRepository.save(c);
        return user;
    }
    public String delete(Long id) {
        User user = userRepository.findById(id).get();
        userRepository.delete(user);

        return "";
    }
}

我的控制器类

@RestController
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping(method = RequestMethod.GET, value = "/users")
    public Iterable<User> user() {
        return userService.contact();
    }

    @RequestMapping(method = RequestMethod.POST, value = "/users")
    public String save(@RequestBody User user) {
        try {
            userService.save(user);
        }catch (org.neo4j.driver.v1.exceptions.ClientException ex){
            System.err.println("******||||||||||||[{   The User exist with the same email   }]||||||||||||******");
        return "The User exist with the same email";
        }
        return user.toString();
    }
    @RequestMapping(method=RequestMethod.GET, value="/users/{id}")
    public User show(@PathVariable Long id) {
        try{
        return userService.show(id);}
        catch (java.util.NoSuchElementException ex){
            System.err.println("******||||||||||||[{   The User do not exist    }]||||||||||||******");
        }
        return null;
    }
    @RequestMapping(method=RequestMethod.PUT, value="/users/{id}")
    public User update(@PathVariable Long id, @RequestBody User user) {
        return userService.update(id, user);
    }
    @RequestMapping(method=RequestMethod.DELETE, value="/users/{id}")
    public String delete(@PathVariable Long id) {
        return userService.delete(id);
    }

}

这是我尝试建模的简单方案(Neo4j是一个NoSQL数据库,没有大纲,但我尝试建模一个简单的应用程序)在这里输入图像描述

当它试图测试api rest的方法时,它对我有效,但是国家实体没有序列化到json。

我已经将数据插入到数据库中,我已经使用一个声明对象的测试方法并使用这些方法保存了数据。当我使用json格式时,问题就出现了。当我运行curl命令测试Rest API时,它不会返回国家/地区

$ curl -i -H "Accept: application/json" localhost:8088/users/1
HTTP/1.1 200
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 27 Sep 2018 20:38:31 GMT

{"created":"2018-09-27T19:55:21.578+0000","id":1,"firstname":"Yuniel","lastname":"Acosta Pérez","email":"yuniel.acosta@someserver.com","phone":"+999999999999","addresses":[{"created":"2018-09-27T19:55:21.578+0000","id":0,"street":"Some Stree","city":"Some City","country":null}]}

如您所见,国家返回它作为空值,如果它存在于数据库中。

当我试图使用API插入一个元素时,它哀叹了一个错误,我无法将country对象序列化为JSON。

$ curl -i -X POST -H "Content-Type: application/json" -d '{"firstname":"Yuniel","lastname":"Acosta Pérez","email":"yuniel.acosta@someserver.com","phone":"+999999999999","addresses":[{"street":"Some Stree","city":"Some City","country":[{"code":"OO","name":"ANYCOUNTRY"}]}]}' localhost:8088/users

下一个错误就是让我

{“时间戳”:“2018-09-27T21:07:56.365 0000”,“状态”:400,“错误”:“错误请求”,“消息”:“JSON解析错误:无法反序列化com.syskayzen.hypercube.domain.Addressout-of-START_数组标记的实例;嵌套异常为com.fasterxml.jackson.databind.exc.MismatchedInputException:无法反序列化com.syskayzen.hypercube.domain.Addressout-of-of-START_数组标记的实例\n位于[源代码:(PushbackInputStream);行:1,列:122](通过引用链:com.syskayzen.hypercube.domain.User[\“addresses\”]),“path”:“/users”}

如果你能告诉我如何解决如何序列化国家实体的问题,或者如果是另一个原因的错误。

我使用的是Spring Boot 2.0.5和Spring Data Neo4j

共有1个答案

邬英武
2023-03-14

我相信在你的curl命令中国家返回空的原因是因为查询在数据库中只有1跳深。所以,它正在拉动用户,然后进行1跳来拉动地址节点,但随后停止。为了让它沿着路径拉更多的啤酒花,你需要指定一个深度。

可以通过在curl命令中指定一个深度,并为“int depth”添加一个参数来传递存储库调用。这将允许你有一个动态的深度,以防你给你的应用程序添加更多你想要检索的跃点。

服务方法看起来像这样。。。。

public User show(Long id, int depth) {
        return userRepository.findById(id, depth).get();
}

以下链接提供了相关文档:https://docs.spring.io/spring-data/neo4j/docs/5.1.0.RELEASE/reference/html/#reference:session:persisting-实体:保存深度

 类似资料:
  • 问题内容: 我正在尝试将文档插入Node.js中的MongoDB中。我已经从数据库中成功读取了文件,并通过命令行界面添加了文档。但是,我无法从JavaScript插入文档。如果这样做,我会收到一个错误: 错误:没有提供的回调无法使用writeConcern 这是我的代码: 我无法终生弄清楚为什么会出现此错误。 我做错了什么,我应该怎么做呢? 问题答案: 您需要为调用提供回调函数,以便该方法可以将插

  • 我对sping-data-neo4j-rest有一个非常简单的问题:因为我在我的@NodeEntity中放置了@RelatedToVia关系,@StartNode和@EndNode出现在我的GET中,就像下面的JSON一样: 我的问题是:为什么会发生这种情况,因为开始节点和结束节点不是节点实体的一部分,我如何防止这种行为发生? 如果我的问题格式不好,请提前道歉,这里的第一个问题,如果有人要求,我将

  • 以下是该实体的: 这是道: 下面是Post映射的详细信息:

  • 问题内容: 我们希望将当前日期时间放入数据库列中。 我们有一个Web场,Web服务器上的时间可以变化,因此我们需要在数据库服务器上使用datetime。 我们有一个带有datetime列的数据库。此列的默认日期时间为当前时间。 当我们使用不包含datetime列的SQL语句插入数据时,这种方法可以很好地工作。 从实体框架: 如果我们将datetime定义为,则datetime设置为低日期,并将低日

  • 使用SpringDataNeo4j,我有两个节点实体:snippet和person。每个片段都有作者。以下是失败的类别和测试: . . .

  • 问题内容: 使用RESTEasy和Jackson,是否可以在模型中使用注释,从而避免根据用户的角色在输出中序列化某些属性? 我已经找到了大量关于如何使用Jersey的文档,但是关于RESTEasy却没有。 我在此架构上受阻,因此切换库不是一个选择,并且也不像此处说明的那样使用自定义,因为该模型足够大,以至于标记大型数据集的每个属性都太耗时用于正确的序列化。另外,这是指Jackson库的较旧版本,我