Slick 编程(5): 数据库Schema

jerry Scala 2015年11月25日 收藏

我们之前Slick 编程(2): 准备开发环境使用自动代码生成工具生成数据库表的Slick定义(使用Lifted Embedding API),本篇介绍如何手工来写这些Schema定义。
数据库表Tables
为了能够使用Slick的Lifted Embedding API定义类型安全的查询,首先我们需要定义数据库表代表表中每行数据的类和对应于数据库表的Schema的TableQuery值,我们先看看自动生成的Album表个相关定义:

  1. /** Entity class storing rows of table Album
  2. * @param albumid Database column AlbumId PrimaryKey
  3. * @param title Database column Title
  4. * @param artistid Database column ArtistId */
  5. case class AlbumRow(albumid: Int, title: String, artistid: Int)
  6. /** GetResult implicit for fetching AlbumRow objects using plain SQL queries */
  7. implicit def GetResultAlbumRow(implicit e0: GR[Int], e1: GR[String]): GR[AlbumRow] = GR{
  8. prs => import prs._
  9. AlbumRow.tupled((<<[Int], <<[String], <<[Int]))
  10. }
  11. /** Table description of table Album. Objects of this class serve as prototypes for rows in queries. */
  12. class Album(tag: Tag) extends Table[AlbumRow](tag, "Album") {
  13. def * = (albumid, title, artistid) <> (AlbumRow.tupled, AlbumRow.unapply)
  14. /** Maps whole row to an option. Useful for outer joins. */
  15. def ? = (albumid.?, title.?, artistid.?).shaped.<>(
  16. {r=>import r._; _1.map(_=> AlbumRow.tupled((_1.get, _2.get, _3.get)))},
  17. (_:Any) => throw new Exception("Inserting into ? projection not supported."))
  18.  
  19. /** Database column AlbumId PrimaryKey */
  20. val albumid: Column[Int] = column[Int]("AlbumId", O.PrimaryKey)
  21. /** Database column Title */
  22. val title: Column[String] = column[String]("Title")
  23. /** Database column ArtistId */
  24. val artistid: Column[Int] = column[Int]("ArtistId")
  25.  
  26. /** Foreign key referencing Artist (database name FK_AlbumArtistId) */
  27. lazy val artistFk = foreignKey("FK_AlbumArtistId", artistid, Artist)
  28. (r => r.artistid, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.NoAction)
  29. }
  30. /** Collection-like TableQuery object for table Album */
  31. lazy val Album = new TableQuery(tag => new Album(tag))

所有的字段(Column)使用column方法来定义,每个字段对应一个Scala类型和一个字段名称(对应到数据库表的定义),下面为Slick支持的基本数据类型: