微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

postgresql – 如何插入UUID的值?

我在播放框架2.3支持 postgresql 9.4中使用anorm 2.4

给这样的模型:

case class EmailQueue(id:UUID,send_from:String,send_to:String,subject:String,body:String,created_date:Date,is_sent:Boolean,email_template:String)

这是我的解析器:

val parser: RowParser[EmailQueue] = {
get[UUID]("id") ~
  get[String]("send_from") ~
  get[String]("send_to") ~
  get[String]("subject") ~
  get[String]("body") ~
  get[Date]("created_date") ~
  get[Boolean]("is_sent") ~
  get[String]("email_template") map {
  case id ~ send_from ~ send_to ~ subject ~ body ~
    created_date ~ is_sent ~ email_template=> EmailQueue(id,send_from,send_to,subject,body,created_date,is_sent,email_template)
}

}

这是我的插入声明:

def insert(email:EmailQueue): Unit ={
DB.withTransaction { implicit c =>
  sql(s"""
        INSERT INTO "email_queue" ( "body","created_date","id","is_sent","send_from","send_to","subject","email_template")
        VALUES ( {body},{created_date},{id},{is_sent},{send_from},{send_to},{subject},{email_template} );
      """).on(
      "body" -> email.body,"created_date" -> email.created_date,"id" -> email.id,"is_sent" -> email.is_sent,"send_from" -> email.send_from,"send_to" -> email.send_to,"subject" -> email.subject,"email_template" -> email.email_template
    ).executeInsert()
}

}

插入时收到以下错误

[error] PsqlException: : ERROR: column “id” is of type uuid but
expression is of type character varying [error] Hint: You will need
to rewrite or cast the expression. [error] Position: 153
(xxxxxxxxxx.java:2270)

数据库表由此查询创建:

CREATE TABLE email_queue (
   id UUID PRIMARY KEY,send_from VARCHAR(255) NOT NULL,send_to VARCHAR(255) NOT NULL,subject VARCHAR(2000) NOT NULL,body text NOT NULL,created_date timestamp without time zone DEFAULT Now(),is_sent BOOLEAN NOT NULL DEFAULT FALSE,email_template VARCHAR(2000) NOT NULL
);

解决方法

Anorm与DB无关,因为JDBC,认情况下不支持特定于供应商的数据类型.

您可以在语句中使用{id} :: uuid,以便在JDBC参数中作为String传递的java.util.UUID然后从传递的VARCHAR转换为特定的Postgresql uuid.

Using string interpolation in sql(s"...") is not recommanded (sql injection),but Anorm interpolation can be used.

def insert(email:EmailQueue): Unit = DB.withTransaction { implicit c =>
  sql"""
    INSERT INTO "email_queue" ( "body","email_template")
    VALUES ( ${email.body},${email.created_date},${email.id}::uuid,${email.is_sent},${email.send_from},${email.send_to},${email.subject},${email.email_template} )
  """).executeInsert()
}

Not recommended,but can be useful sometimes for vendor specific type,the anorm.Object can be used to pass an opaque value as JDBC parameter (there the ::uuid is nicer for me).

You can also implement a custom ToStatement[java.util.UUID].

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐