2016-03-29 22 views
0

我是Scala和Play框架的新手。我嘗試從數據表中查詢所選列的所有數據,並將它們保存爲Excel文件。Anorm:隱式轉換[all value(include null)]到[String]

所選列通常有不同的類型,如int,STR,時間戳等

我想轉換所有的值類型,包括空轉換成String (零轉換爲空字符串「」) 不知道一列的實際類型,所以代碼可以用於任何表。

根據Play的文檔,我可以在下面編寫隱式轉換器,但是,這不能處理null。長期搜索這個,找不到解決方案。有人可以讓我知道如何處理隱式轉換器中的null?

預先感謝〜

implicit def valueToString: anorm.Column[String] = 
    anorm.Column.nonNull1[String] { (value, meta) => 
     val MetaDataItem(qualified, nullable, clazz) = meta 
     value match { 
      case s: String    => Right(s) // Provided-default case 
      case i: Int     => Right(i.toString()) // Int to String 
      case t: java.sql.Clob  => Right(t.toString()) // Blob/Text to String 
      case d: java.sql.Timestamp => Right(d.toString()) // Datatime to String 
      case _      => Left(TypeDoesNotMatch(s"Cannot convert $value: ${value.asInstanceOf[AnyRef].getClass} to String for column $qualified")) 
     } 

    } 
+0

您在運行時看到什麼錯誤? – tryx

+0

錯誤消息:java.lang.RuntimeException:Left(UnexpectedNullableFound(ColumnName(.valuea,Some(valuea)))) at anorm.MayErr $$ anonfun $ get $ 1.apply(MayErr.scala:35) – WeiJ

回答

1

documentation指示的,如果有一個Column[T],允許解析T類型的柱,並且如果列(多個)可以爲空,然後Option[T]應問道,受益於Option[T]的通用支持。

那裏是自定義Column[String](請確保使用自定義的一個,而不是提供的Column[String]),因此應該詢問Option[String]

import myImplicitStrColumn 
val parser = get[Option[String]]("col") 
+0

嗨cchantep,是的,我試過這個:'隱式def valueToString:anorm.Column [Option [String]] = anorm.Column.nonNull1 [Option [String]] {(value,meta)=> val MetaDataItem(合格,可爲空, )= meta case match s:Option [String] => ... case i:Option [Int] => ... case t:Option [java.sql.Clob] => .. = case d:Option [java.sql.Timestamp] => ... case _ => .. } }''但是出現錯誤「無法將Int轉換爲字符串....」 – WeiJ

+0

如上所述,您不應該使用通用的Option來定義一個Column [Option [T]],而是一個Column [T]'+ '支持 – cchantep

+0

我明白了......謝謝〜我會試一試......我認爲Anorm可能會提供更簡單的方法來處理null,因爲這很常見。 – WeiJ