2017-04-14 36 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