5

我尝试了 Luanne 的文章Scala中 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。你能指出我代码中的问题吗?

谢谢,

马诺伊。

4

2 回答 2

2

Scala 的 Long 是 Value 类的一个实例。明确引入了值类以避免分配运行时对象。因此,在 JVM 级别,ScalaLong等同于 Java 的原语long,这就是它具有原语类型签名的原因 J。因此它不能为 null,也不应该用作graphId. 尽管 Scala 主要会在自己的类Long和 Java 的Long类之间进行自动装箱,但这不适用于声明,仅适用于对这些对象的操作。

于 2015-08-14T08:54:03.527 回答
0

@GraphId没有在您的实体上接收到。我对Scala的了解为零,但看起来OGM不太喜欢scala long;var id: java.lang.Long = _工作正常。

于 2015-08-14T04:27:02.803 回答