从数据库读取时Scala案例类相等

时间:2017-04-14 00:54:46

标签: scala gremlin

我在检查我已经映射到apache tinkerpop图的案例类上是否有相同的问题,但是我希望能够在查询图表后检查是否相等。

@label("apartment")
case class Apartment(@id id: Option[Int], address: String, zip: Zip, rooms: Rooms, size: Size, price: Price, link: String, active: Boolean = true, created: Date = new Date()) {}
val ApartmentAddress = Key[String]("address")

Await.result(result, Duration.Inf).foreach(apt => {
    val dbResult = graph.V.hasLabel[Apartment].has(ApartmentAddress, apt.address).head().toCC[Apartment]
    println(dbResult == apt)  //always false :(
  })

我的问题是,当我创建了它没有id的对象时,它上面的时间戳明显不同。我读过如果你添加第二个参数列表,它会从equals中排除,所以我改了它:

@label("apartment")
case class Apartment(address: String, zip: Zip, rooms: Rooms, size: Size, price: Price, link: String, active: Boolean = true)(@id implicit val  id: Option[Int] = None, implicit val created: Date = new Date()) {}
val ApartmentAddress = Key[String]("address")

Await.result(result, Duration.Inf).foreach(apt => {
    val dbResult = graph.V.hasLabel[Apartment].has(ApartmentAddress, apt.address).head().toCC[Apartment]
    println(dbResult == apt)  //true! yay! :D
  })

我现在可以使用==检查是否相等,但是数据库中的值丢失了它的id,并且"创建了"值被重置。而另一个令人沮丧的事情是,它们总是需要在最后用括号创建:

Apartment(address, zip, rooms, size, price, link)()

有没有办法在没有重载等于的情况下实现此功能?或者使用这种方法使数据库中的值保持原始值?

1 个答案:

答案 0 :(得分:3)

在您的情况下,您似乎只需要进行一次比较,因此我不会使用等于和比较修改后的值

case class Apartment(
    @id id: Option[Int] = None,
    address: String,
    zip: Zip,
    rooms: Rooms,
    size: Size,
    price: Price,
    link: String,
    active: Boolean = true,
    created: Date = new Date(0)) {
}

println(dbResult.copy(id = None, created = new Date(0)) == apt)  //true! yay! :D

或在课程中添加额外的功能

case class Apartment(
    @id id: Option[Int] = None,
    address: String,
    zip: Zip,
    rooms: Rooms,
    size: Size,
    price: Price,
    link: String,
    active: Boolean = true,
    created: Date = new Date(0)) {

    def equalsIgnoreIdAndCreated(other: Apartment) = {
       this.equals(other.copy(id = id, created = created))
    }
}

println(dbResult.equalsIgnoreIdAndCreated(apt))

您可以查看案例类的详细解释 http://www.alessandrolacava.com/blog/scala-case-classes-in-depth/以及为什么不应该自动生成覆盖等于的原因,否则只是覆盖等于。