0

我在 H2 中有这张表:

CREATE TABLE computer (id BIGINT NOT NULL, name VARCHAR(255) NOT NULL, introduced TIMESTAMP, discontinued TIMESTAMP, company_id BIGINT, CONSTRAINT pk_computer PRIMARY KEY (id));
CREATE SEQUENCE computer_seq START WITH 1000;

光滑的自动生成的类:

  case class ComputerRow(id: Long, name: String, introduced: Option[java.sql.Timestamp], discontinued: Option[java.sql.Timestamp], companyId: Option[Long])
  /** GetResult implicit for fetching ComputerRow objects using plain SQL queries */
  implicit def GetResultComputerRow(implicit e0: GR[Long], e1: GR[String], e2: GR[Option[java.sql.Timestamp]], e3: GR[Option[Long]]): GR[ComputerRow] = GR{
    prs => import prs._
    ComputerRow.tupled((<<[Long], <<[String], <<?[java.sql.Timestamp], <<?[java.sql.Timestamp], <<?[Long]))
  }
  /** Table description of table COMPUTER. Objects of this class serve as prototypes for rows in queries. */
  class Computer(tag: Tag) extends Table[ComputerRow](tag, "COMPUTER") {
    def * = (id, name, introduced, discontinued, companyId) <> (ComputerRow.tupled, ComputerRow.unapply)
    /** Maps whole row to an option. Useful for outer joins. */
    def ? = (id.?, name.?, introduced, discontinued, companyId).shaped.<>({r=>import r._; _1.map(_=> ComputerRow.tupled((_1.get, _2.get, _3, _4, _5)))}, (_:Any) =>  throw new Exception("Inserting into ? projection not supported."))

    /** Database column ID PrimaryKey */
    val id: Column[Long] = column[Long]("ID", O.PrimaryKey)
    /** Database column NAME  */
    val name: Column[String] = column[String]("NAME")
    /** Database column INTRODUCED  */
    val introduced: Column[Option[java.sql.Timestamp]] = column[Option[java.sql.Timestamp]]("INTRODUCED")
    /** Database column DISCONTINUED  */
    val discontinued: Column[Option[java.sql.Timestamp]] = column[Option[java.sql.Timestamp]]("DISCONTINUED")
    /** Database column COMPANY_ID  */
    val companyId: Column[Option[Long]] = column[Option[Long]]("COMPANY_ID")

    /** Foreign key referencing Company (database name FK_COMPUTER_COMPANY_1) */
    lazy val companyFk = foreignKey("FK_COMPUTER_COMPANY_1", companyId, Company)(r => r.id, onUpdate=ForeignKeyAction.Restrict, onDelete=ForeignKeyAction.Restrict)
  }
  /** Collection-like TableQuery object for table Computer */
  lazy val Computer = new TableQuery(tag => new Computer(tag))

但是,我似乎无法插入新行。下面的尝试

val row = ("name", new Timestamp((new Date).getTime), new Timestamp((new Date).getTime), 123)

DB.withDynSession {
    Computer.map( r =>
        (r.name, r.introduced, r.discontinued, r.companyId)
    ) += row
}

引发错误

[JdbcSQLException: NULL not allowed for column "ID"; SQL statement: INSERT INTO "COMPUTER" ("NAME","INTRODUCED","DISCONTINUED","COMPANY_ID") VALUES (?,?,?,?) [23502-175]]

同样的方法适用于 MySQL 和 PostgreSQL,所以我猜 H2 没有相同的主 ID 自动递增功能?那么如何使我的插入与光滑一起工作?

这是使用 Anorm 的同一张表的工作示例:

DB.withConnection { implicit connection =>
    SQL(
        """
            insert into computer values (
                (select next value for computer_seq), 
                {name}, {introduced}, {discontinued}, {company_id}
            )
        """
    ).on(
        'name -> "name",
        'introduced -> new Timestamp((new Date).getTime),
        'discontinued -> new Timestamp((new Date).getTime),
        'company_id -> 123
    ).executeUpdate()
}
4

2 回答 2

1

据我所知,这不是一个 Slick 问题,但是您的 DDL 语句没有为 H2 指定自动增量。检查示例项目的 play-slick SQL 代码:https ://github.com/playframework/play-slick/blob/master/samples/computer-database/conf/evolutions/default/1.sql

还要检查 H2 文档:http ://www.h2database.com/html/grammar.html#column_definition

于 2014-06-13T13:24:28.327 回答
0

尝试为案例类赋予 id 的默认值,如下所示:

case class ComputerRow(id: Long = 0, name: String, introduced: Option[java.sql.Timestamp], discontinued: Option[java.sql.Timestamp], companyId: Option[Long])

我不确定,H2但是当我使用时,Postgres我通常指定id字段的默认值以符合 Slick 的最终检查,然后在数据库端,值插入由序列自动处理。

编辑:

我可能错了,但我注意到您创建了一个序列而不分配它:

CREATE TABLE computer (id BIGINT NOT NULL, name VARCHAR(255) NOT NULL, introduced TIMESTAMP, discontinued TIMESTAMP, company_id BIGINT, CONSTRAINT pk_computer PRIMARY KEY (id));
CREATE SEQUENCE computer_seq START WITH 1000;

Postgres您创建序列,然后分配它们像这样:

create table users (
  id  bigint not null
);

create sequence users_seq;
alter table users alter column id set default nextval('users_seq');

据我所知,H2这是您分配自动增量的方式:

create table test(id bigint auto_increment, name varchar(255));

采取这个 SO question的形式。

于 2014-06-13T11:17:45.137 回答