我正在尝试使用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
。在此类中用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>
我缺少明显的东西吗?您如何解决这个问题?
答案 0 :(得分:0)
我遇到了这个完全相同的问题。不确定确切的根本原因,但这似乎是OGM + Kotlin中的错误。我用一个转换器将其修复,该转换器告诉OGM将其转换为String数组以存储在Neo4J中。像这样:
标记您的媒体资源以使用转换器:
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()
}
转换器:
{{1}}