如何插入UUID的值?

时间:2015-06-22 16:53:21

标签: postgresql scala playframework anorm

我在播放框架2.3中使用anorm 2.4支持postgresql 9.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:列“id”的类型为uuid但是   表达式是字符变化的类型[错误]提示:您将需要   重写或转换表达式。 [错误]位置: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
);

1 个答案:

答案 0 :(得分:7)

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

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

  

不建议在SQL(s"...")中使用字符串插值(SQL注入),但可以使用Anorm插值。

def insert(email:EmailQueue): Unit = DB.withTransaction { implicit c =>
  SQL"""
    INSERT INTO "email_queue" ( "body", "created_date", "id", "is_sent", "send_from", "send_to", "subject", "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()
}
  

不推荐,但有时对于供应商特定类型有用,anorm.Object可用于将不透明值作为JDBC参数传递(::uuid对我来说更好)。

     

您还可以实施自定义ToStatement[java.util.UUID]