2017-04-14 54 views
1

我在检查案例类,我已映射到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 :(
    }) 

我的问题是,当我创建对象时,它没有身份证,它的时间戳明显不同。我读,如果你添加第二个参数列表,它是从平等排除在外,所以我改成了:

@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)() 

有没有办法实现,而不会加重等于该功能?或者使用这种方法使数据库中的值保持原始值?

回答

3

看来你的情况,你只需要它只是一个时间比较,所以我不会与equals玩,只是修改的值上比较

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/中查看案例分类的好解释,以及您不应该自动生成覆盖等于的原因,否则只是覆盖等于。

+0

完美!谢谢! – Raudbjorn