本文来自 http://fair-jm.iteye.com 转截请注明出处
本文是slick2 笔记1和2的补充 在实际使用下的一些操作
使用SourceCodeGenerator生成实体和操作类
这个类没有提供用户名和密码的参数 所以需要自己改写一个
直接根据scala.slick.model.codegen.SourceCodeGenerator改就可以了
一个例子:
package mysql_sourceGen import scala.slick.{ model => m } import scala.slick.model.codegen._ class MySQLSourceCodeGenerator(model: m.Model) extends AbstractSourceCodeGenerator(model) with OutputHelpers { type Table = TableDef def Table = new TableDef(_) class TableDef(model: m.Table) extends super.TableDef(model) { type EntityType = EntityTypeDef def EntityType = new EntityType {} type PlainSqlMapper = PlainSqlMapperDef def PlainSqlMapper = new PlainSqlMapper {} type TableClass = TableClassDef def TableClass = new TableClass {} type TableValue = TableValueDef def TableValue = new TableValue {} type Column = ColumnDef def Column = new Column(_) type PrimaryKey = PrimaryKeyDef def PrimaryKey = new PrimaryKey(_) type ForeignKey = ForeignKeyDef def ForeignKey = new ForeignKey(_) type Index = IndexDef def Index = new Index(_) } } object MySQLSourceCodeGenerator { import scala.slick.driver.JdbcProfile import scala.reflect.runtime.currentMirror def main(args: Array[String]) = { args.toList match { case List(slickDriver, jdbcDriver, url, outputFolder, pkg, user, pass) => { val driver: JdbcProfile = { val module = currentMirror.staticModule(slickDriver) val reflectedModule = currentMirror.reflectModule(module) val driver = reflectedModule.instance.asInstanceOf[JdbcProfile] driver } driver.simple.Database .forURL(url, driver = jdbcDriver, password = pass, user = user) .withSession { implicit session => (new SourceCodeGenerator(driver.createModel)).writeToFile(slickDriver, outputFolder, pkg) } } case _ => { println(""" Usage: SourceCodeGenerator.main(Array( slickDriver, jdbcDriver, url, outputFolder, pkg )) slickDriver: Fully qualified name of Slick driver class, e.g. "scala.slick.driver.H2Driver" jdbcDriver: Fully qualified name of jdbc driver class, e.g. "org.h2.Driver" url: jdbc url, e.g. "jdbc:postgresql://localhost/test" outputFolder: Place where the package folder structure should be put pkg: Scala package the generated code should be places in user: DataBase's username pass : the user's password """.trim) } } } }
我起的名字有歧义 这个不只是mysql可以用 所有都可以用 你传入driver的字符串就可以了
多表以及分页查询的例子:
SlickDB.database.withSession { implicit session => val query = for { cid <- Tables.Category.filter(_.name === tag).map(_.id) aids <- Tables.ArticleCategory.filter(_.cId === cid).map(_.aId) article <- Tables.Article.filter(_.id === aids) } yield article ((query.length.run-1) /Constants.PageSize +1, query.sortBy(_.time desc).drop((page - 1) * Constants.PageSize).take(Constants.PageSize).list) }
从tag表拿出tag得到对应的cid 根据对应的cid找到文章的aid 根据文章的id得到文章
多对多查询有中间表时使用的例子
后面的分页 按照时间降序 得到第page(从1开始)页的数据
插入得到id的例子:
val aid = (Tables.Article returning Tables.Article.map(_.id)) += article
类似于postgresql的 returnning