我尝试了Luanne的文章The essence of Spring Data Neo4j 4 in Scala中提到的示例。代码可以在neo4j-ogm-scala存储库中找到。
package neo4j.ogm.scala.domain
import org.neo4j.ogm.annotation.GraphId;
import scala.beans.BeanProperty
import org.neo4j.ogm.annotation.NodeEntity
import org.neo4j.ogm.annotation.Relationship
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
abstract class Entity {
@GraphId
@BeanProperty
var id: Long = _
override def equals(o: Any): Boolean = o match {
case other: Entity => other.id.equals(this.id)
case _ => false
}
override def hashCode: Int = id.hashCode()
}
@NodeEntity
class Category extends Entity {
var name: String = _
def this(name: String) {
this()
this.name = name
}
}
@NodeEntity
class Ingredient extends Entity {
var name: String = _
@Relationship(`type` = "HAS_CATEGORY", direction = "OUTGOING")
var category: Category = _
@Relationship(`type` = "PAIRS_WITH", direction = "UNDIRECTED")
var pairings: Set[Pairing] = Set()
def addPairing(pairing: Pairing): Unit = {
pairing.first.pairings +(pairing)
pairing.second.pairings +(pairing)
}
def this(name: String, category: Category) {
this()
this.name = name
this.category = category
}
}
@RelationshipEntity(`type` = "PAIRS_WITH")
class Pairing extends Entity {
@StartNode
var first: Ingredient = _
@EndNode
var second: Ingredient = _
def this(first: Ingredient, second: Ingredient) {
this()
this.first = first
this.second = second
}
}
object Neo4jSessionFactory {
val sessionFactory = new SessionFactory("neo4j.ogm.scala.domain")
def getNeo4jSession(): Session = {
System.setProperty("username", "neo4j")
System.setProperty("password", "neo4j")
sessionFactory.openSession("http://localhost:7474")
}
}
object Main extends App {
val spices = new Category("Spices")
val turmeric = new Ingredient("Turmeric", spices)
val cumin = new Ingredient("Cumin", spices)
val pairing = new Pairing(turmeric, cumin)
cumin.addPairing(pairing)
val session = Neo4jSessionFactory.getNeo4jSession()
val tx: Transaction = session.beginTransaction()
try {
session.save(spices)
session.save(turmeric)
session.save(cumin)
session.save(pairing)
tx.commit()
} catch {
case e: Exception => // tx.rollback()
} finally {
// tx.commit()
}
}问题是没有任何东西被保存到Neo4j中。你能指出我代码中的问题吗?
谢谢,
马诺杰。
发布于 2015-08-14 16:54:04
Scala的Long是一个值类的实例。显式引入值类是为了避免分配运行时对象。因此,在JVM级别,Scala的Long等同于Java的原语long,这就是为什么它具有原语类型签名J的原因。因此,它不能为null,并且不应用作graphId。尽管Scala主要会在自己的Long和Java的Long类之间进行自动装箱,但这并不适用于声明,只适用于对这些对象的操作。
发布于 2015-08-14 12:27:03
你的实体上没有接收到@GraphId。我对Scala一无所知,但是看起来scala long不太受OGM喜欢;var id: java.lang.Long = _运行得很好。
https://stackoverflow.com/questions/31989802
复制相似问题