![](/img/trans.png)
[英]Is there an example of using an hstore data structure with scalikejdbc and postgres?
[英]How to save record in postgres with custom type using scalikejdbc?
就我而言,我在postgres中有一個枚舉類型:
create type my_type as enum (string value);
和一些表,使用此作為列類型:
create table A (
...
t my_type,
...
)
在postgres中,我可以像這樣在表A中插入新記錄:
insert into A values(..., 'my_type_value', ...);
Scalikejdbc生成正確的sql:
insert into A (...) values (..., 'my_type_value', ...)
但是失敗並顯示錯誤:
錯誤:列“ t”的類型為my_type,但表達式的類型字符不同提示:您將需要重寫或強制轉換表達式。
我試圖這樣做:
object MyType extends Enumeration {...}
case class A(..., t: MyType, ...)
object A extends SQLSyntaxSupport[A] {
def apply(rs: WrappedResultSet): A = A(..., rs.getString('t'), ...)
}
此外,我試圖在Scala代碼中以枚舉類型添加隱式轉換:
object MyType extends Enumeration {
implicit def stringToValue...
implicit def valueToString ...
}
但這也沒有幫助。
插入代碼如下所示:
withSQL {
insertInto(A).namedValues(
...
A.column.t-> e.t, // e - passed entity into insert fun
....
)
}.update().apply()
最后解決了。 我必須添加隱式轉換器:
implicit val valueToParameterBinder: ParameterBinderFactory[MyType] = ParameterBinderFactory {
value => (stmt, indx) => stmt.setObject(indx, value, Types.OTHER)
}
object A extends SQLSyntaxSupport[A] {
def apply(rs: WrappedResultSet): A = A(..., rs.getString('t'), ...) // just call getString as usual
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.