因为autoInc 可能会造成混淆,我将为您提供一个工作示例(请注意,我的数据库是 PostgreSQL,所以我需要使用forInsert 进行破解,以使 Postgresql 驱动程序增加 auto-inc 值)。
case class GeoLocation(id: Option[Int], latitude: Double, longitude: Double, altitude: Double)
/**
* Define table "geo_location".
*/
object GeoLocations extends RichTable[GeoLocation]("geo_location") {
def latitude = column[Double]("latitude")
def longitude = column[Double]("longitude")
def altitude = column[Double]("altitude")
def * = id.? ~ latitude ~ longitude ~ altitude <> (GeoLocation, GeoLocation.unapply _)
def forInsert = latitude ~ longitude ~ altitude <> ({ (lat, long, alt) => GeoLocation(None, lat, long, alt) },
{ g: GeoLocation => Some((g.latitude, g.longitude, g.altitude)) })
}
我的 RichTable 是一个抽象类,以便不为我拥有的每个表声明 id,而只是扩展它:
abstract class RichTable[T](name: String) extends Table[T](name) {
def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
val byId = createFinderBy(_.id)
}
并像这样使用它:
GeoLocations.forInsert.insert(GeoLocation(None, 22.23, 25.36, 22.22))
由于您将None 传递给id,所以当Slick 插入这个新实体时,它将由PostgreSql 驱动程序自动生成。
我开始使用 Slick 已经有几个星期了,我真的推荐它!
更新:如果您不想使用forInsert 投影,另一种方法如下 - 在我的情况下,实体是Address。
在创建模式时为每个表创建序列:
session.withTransaction {
DBSchema.tables.drop
DBSchema.tables.create
// Create schemas to generate ids too.
Q.updateNA("create sequence address_seq")
}
定义一个使用序列生成 id 的方法(我在 RichTable 类中定义了这个 once:
def getNextId(seqName: String) = Database { implicit db: Session =>
Some((Q[Int] + "select nextval('" + seqName + "_seq') ").first)
}
并在映射器中覆盖 insert 方法,如:
def insert(model : Address) = Database { implicit db: Session =>
*.insert(model.copy(id = getNextId(classOf[Address].getSimpleName())))
}
现在,您可以在执行插入操作时传递 None,这些方法会为您提供很好的工作...