Neo4j Spring Data NodeEntity使用String作为@id

时间:2018-03-21 07:54:12

标签: neo4j spring-data spring-data-neo4j

我试图使用java.lang.String作为NodeEntity的@Id。

While an id is still required on all entities, the behavior has been
simplified by introducing the new @Id annotation. It replaces both
@GraphId and the primary attribute and can be placed on any attribute 
with a simple type.

应该可以根据弹簧数据neo4j document:

{
    "cause": null,
    "message": "Id must be assignable to Serializable!: null"
}

当我试图插入时,我得到一个:

$ git checkout -b hotfix/my-branch -t origin/master
$ mkdir test_folder
$ touch test_folder/test.php
$ git add test_folder
$ git commit -m "adding test"
$ git push -u origin HEAD

这很奇怪,因为String实现了Serializable。 任何人都知道在哪里搜索?

1 个答案:

答案 0 :(得分:0)

我认为您不能将任何其他内容用作ID。请记住,如果删除节点,将重复使用此长号。

我使用UUID插件生成真正的唯一键,当我使用spring-data-rest时,我使用BackendIdConverter将id更改为我公开的资源的uuid。

实施例: 型号:

@NodeEntity
@Data
public class Target {

    @Id @GeneratedValue Long id;   // <----Neo4j id 

    private String uuid;           // <----My Key

    @Version Long version;
    private List<String> labels = new ArrayList<>();
    @Relationship(type = "HAS_MEDIA", direction=Relationship.OUTGOING)
    private List<Gallery> media = new ArrayList<>();

}

将资源ID转换为我的密钥:

@Component 
public class MovieIdConverter implements BackendIdConverter {
    @Autowired MovieRepo movieRepository;

    @Override
    public Serializable fromRequestId(String id, Class<?> entityType) {
        Movie movie = movieRepository.findByUuid(id);
        return  (Serializable) movie.getId();
    }

    @Override
    public String toRequestId(Serializable serializable, Class<?> aClass) {
        Long id = (Long) serializable;
        Optional<Movie> movie = movieRepository.findById(id);
        if (movie.isPresent()) return movie.get().getUuid();
        return null;
}

    @Override
    public boolean supports(Class<?> aClass) {
        return Movie.class.equals(aClass);
    }
}