我在Scala中尝试了Luanne的文章The essence of Spring Data Neo4j 4中提到的示例。代码可以在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。你可以在我的代码中指出问题吗?
谢谢,
的Manoj。
答案 0 :(得分:2)
Scala的Long是Value类的一个实例。显式引入了值类以避免分配运行时对象。因此,在JVM级别,Scala的Long
等同于Java的原始long
,这就是它具有原始类型签名J
的原因。因此它不能为空,不应该用作graphId
。虽然Scala主要在自己的Long
和Java的Long
类之间进行自动装箱,但这不适用于声明,只适用于对这些对象的操作。
答案 1 :(得分:0)
您的实体未获取@GraphId
。我对Scala一无所知,但看起来像OGM不太喜欢Scala; var id: java.lang.Long = _
工作正常。