Neo4j OGM - 反序列化 Kotlin 中的枚举列表

Neo4j OGM - Deserializing enum lists in Kotlin

我正在尝试使用 Kotlin 在 Neo4j 数据库中存储和检索具有枚举列表的对象。使用枚举存储实体工作正常,但将其反序列化回同一个枚举并不像我在 Kotlin 中尝试的那样工作。我正在使用螺栓起子。

enum class DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

@NodeEntity
data class Weekend(
  @Id @GeneratedValue var id: Long? = null, 
  var days: List<DayOfWeek>? = null
)

fun main(args: Array<String>) {
  val config = Configuration.Builder()
    .uri("bolt://localhost:7687")
    .credentials("username", "password")
    .build()
  val sessionFactory = SessionFactory(config, "com.example.calendar")
  val session = sessionFactory.openSession()
  val weekend = session.load(Weekend::class.java, 10L)
  weekend.days?.forEach { print("The weekend consists of: $it") }
}

这样做只会引发异常:Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to com.example.calendar.DayOfWeek。用这个 class 在 Java 中做同样的事情很好:

public class WeekendJ {
  @Id
  @GeneratedValue
  Long id;
  List<DayOfWeek> days;
  public WeekendJ() {
  }
  public WeekendJ(List<DayOfWeek> days) {
    this.days = days;
  }
}

我的 POM:

<dependency>
  <groupId>org.neo4j</groupId>
  <artifactId>neo4j-ogm-core</artifactId>
  <version>3.1.5</version>
  <scope>compile</scope>
</dependency>

<dependency>
  <groupId>org.neo4j</groupId>
  <artifactId>neo4j-ogm-bolt-driver</artifactId>
  <version>3.1.5</version>
  <scope>runtime</scope>
</dependency>

<dependency>
  <groupId>org.jetbrains.kotlin</groupId>
  <artifactId>kotlin-stdlib-jdk8</artifactId>
  <version>1.3.11</version>
</dependency>

我是不是遗漏了什么明显的东西?你是如何解决 Kotlin 问题的?

我 运行 遇到了这个完全相同的问题。不确定确切的根本原因,但它似乎是 OGM+Kotlin 中的错误。我用一个转换器修复了它,该转换器告诉 OGM 将其转换为字符串数组以存储在 Neo4J 中。像这样:

标记您的 属性 以使用转换器:

public class WeekendJ {
  @Id
  @GeneratedValue
  Long id;

  @Convert(DayOfWeekConverter::class)
  List<DayOfWeek> days;

  public WeekendJ() {
  }
  public WeekendJ(List<DayOfWeek> days) {
    this.days = days;
  }
}

转换器:

class DayOfWeek : AttributeConverter<Set<DayOfWeek>, Array<String>> {
    override fun toGraphProperty(days: Set<DayOfWeek>): Array<String> =
            days.map { it.name }.toTypedArray()

    override fun toEntityAttribute(dayNames: Array<String>): Set<DayOfWeek> =
            dayNames.map { DayOfWeek.valueOf(it) }.toSet()
}