我们之前Slick 编程(2): 准备开发环境使用自动代码生成工具生成数据库表的Slick定义(使用Lifted Embedding API),本篇介绍如何手工来写这些Schema定义。
数据库表Tables
为了能够使用Slick的Lifted Embedding API定义类型安全的查询,首先我们需要定义数据库表代表表中每行数据的类和对应于数据库表的Schema的TableQuery值,我们先看看自动生成的Album表个相关定义:
- /** Entity class storing rows of table Album
- * @param albumid Database column AlbumId PrimaryKey
- * @param title Database column Title
- * @param artistid Database column ArtistId */
- case class AlbumRow(albumid: Int, title: String, artistid: Int)
- /** GetResult implicit for fetching AlbumRow objects using plain SQL queries */
- implicit def GetResultAlbumRow(implicit e0: GR[Int], e1: GR[String]): GR[AlbumRow] = GR{
- prs => import prs._
- AlbumRow.tupled((<<[Int], <<[String], <<[Int]))
- }
- /** Table description of table Album. Objects of this class serve as prototypes for rows in queries. */
- class Album(tag: Tag) extends Table[AlbumRow](tag, "Album") {
- def * = (albumid, title, artistid) <> (AlbumRow.tupled, AlbumRow.unapply)
- /** Maps whole row to an option. Useful for outer joins. */
- def ? = (albumid.?, title.?, artistid.?).shaped.<>(
- {r=>import r._; _1.map(_=> AlbumRow.tupled((_1.get, _2.get, _3.get)))},
- (_:Any) => throw new Exception("Inserting into ? projection not supported."))
- /** Database column AlbumId PrimaryKey */
- val albumid: Column[Int] = column[Int]("AlbumId", O.PrimaryKey)
- /** Database column Title */
- val title: Column[String] = column[String]("Title")
- /** Database column ArtistId */
- val artistid: Column[Int] = column[Int]("ArtistId")
- /** Foreign key referencing Artist (database name FK_AlbumArtistId) */
- lazy val artistFk = foreignKey("FK_AlbumArtistId", artistid, Artist)
- (r => r.artistid, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.NoAction)
- }
- /** Collection-like TableQuery object for table Album */
- lazy val Album = new TableQuery(tag => new Album(tag))
所有的字段(Column)使用column方法来定义,每个字段对应一个Scala类型和一个字段名称(对应到数据库表的定义),下面为Slick支持的基本数据类型: