O.AutoInc, O.PrimaryKey)
21
22 def title = column[String]("TITLE")
23
24 def year = column[Option[Int]]("YEAR")
25
26 def artist = column[String]("ARTIST", O.Default("Unknown"))
27
28 def * = (id, artist, year, title) <> (AlbumModel.tupled, AlbumModel.unapply)
29 }
30
31 //库表实例
32 val albums = TableQuery[AlbumTable]
33
34 //创建表动作
35 val createTableAction = albums.schema.create
36
37 //数据库实例化
38 val db = Database.forConfig("h2")
39
40 //插入数据动作
41 val insertAlbumsAction =
42 albums ++= Seq(
43 AlbumModel(0, "Keyboard Cat", Some(2003), "Keyboard Cat's Greatest Hits"),
44 AlbumModel(0, "Spice Girls", Some(2010), "Spice"),
45 AlbumModel(0, "Rick Astley", Some(1998), "Whenever You Need Somebody"),
46 AlbumModel(0, "Manowar", None,"The Triumph of Steel"),
47 AlbumModel(0, "Justin Bieber", Some(2011),"Believe"))
48
49 //数据抽取动作
50 val selectAlbumsAction =
51 albums.result
52
53 def printResults[T](fut: Future[Iterable[T]]): Unit =
54 Await.result(fut, Duration.Inf).foreach(println)
55
56 def main(args: Array[String]): Unit = {
57
58 val res = db.run(createTableAction).andThen {
59 case Success(_) => println("table ALBUMS created.")
60 case Failure(e) => println(e.getMessage)
61 }
62 Await.result(res, 10 seconds)
63
64 val res2 = db.run(insertAlbumsAction).andThen {
65 case Success(_) => println("albums inserted.")
66 case Failure(e) => println(e.getMessage)
67 }
68 Await.result(res2, 10 seconds)
69
70 val res3 = db.run(selectAlbumsAction)
71 printResults(res3)
72 }
73 }
|