【问题标题】:Neo4j Spring Data NodeEntity use String as @idNeo4j Spring Data NodeEntity 使用字符串作为@id
【发布时间】:2018-08-30 05:58:42
【问题描述】:

我正在尝试使用 java.lang.String 作为 NodeEntity 的 @Id。

 @NodeEntity(label = "MachineType")
 public class MachineType {
     @Id private String id;
     ....

根据spring数据neo4j文档应该是可以的:

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.

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

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

这很奇怪,因为 String 实现了 Serializable。 有人知道下一步该去哪里搜索吗?

【问题讨论】:

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


    【解决方案1】:

    我认为您不能使用其他任何东西作为 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-08
      • 2013-09-23
      • 1970-01-01
      • 2015-07-19
      • 2016-01-05
      • 2019-02-17
      • 1970-01-01
      • 1970-01-01
      • 2015-04-18
      相关资源
      最近更新 更多