1. 程式人生 > >Scala入門到精通——第二十九節 Scala數據庫編程

Scala入門到精通——第二十九節 Scala數據庫編程

while mic hibernate using 框架 batch mes dcl ant

本節主要內容

  1. Scala Mavenproject的創建
  2. Scala JDBC方式訪問MySQL
  3. Slick簡單介紹
  4. Slick數據庫編程實戰
  5. SQL與Slick相互轉換

本課程在多數內容是在官方教程上改動而來的,官方給的樣例是H2數據庫上的。經過本人改造,用在MySQL數據庫上,官方教程地址:http://slick.typesafe.com/doc/2.1.0/sql-to-slick.html

1. Scala Mavenproject的創建

本節的project項目採用的是Maven Project,在POM.xml文件裏加入以下兩個依賴就能夠使用scala進行JDBC方式及Slick框架操作MySQL數據庫:

 <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.18</version>
     </dependency>
     <dependency>
    <groupId>com.typesafe.slick</groupId>
    <artifactId>slick_2.11</artifactId
>
<version>2.1.0</version> </dependency>

scala IDE for eclipse 中創建scala Maven項目的方式例如以下:
在Eclispe 中點擊” File->new->other”。例如以下圖
技術分享
輸入Maven能夠看到Maven Project:

技術分享
直接next。得到
技術分享
再點擊next,在filter中輸入scala得到:
技術分享
選中,然後next輸入相應的groupId等。直接finish就可以。創建完項目將上述依賴加入到pom.xml文件其中。這樣就完畢了scala maven Project的創建。

2. Scala JDBC方式訪問MySQL

以下給出的是scala採用JDBC訪問MySQL的代碼演示樣例

package cn.scala.xtwy.jdbc

import java.sql.{ Connection, DriverManager }
object ScalaJdbcConnectSelect extends App {
  // 訪問本地MySQLserver,通過3306端口訪問mysql數據庫
  val url = "jdbc:mysql://localhost:3306/mysql"
  //驅動名稱
  val driver = "com.mysql.jdbc.Driver"
  //用戶名
  val username = "root"
  //密碼
  val password = "123"
  //初始化數據連接
  var connection: Connection = _
  try {
   //註冊Driver
    Class.forName(driver)
    //得到連接
    connection = DriverManager.getConnection(url, username, password)
    val statement = connection.createStatement
    //運行查詢語句,並返回結果
    val rs = statement.executeQuery("SELECT host, user FROM user")
    //打印返回結果
    while (rs.next) {
      val host = rs.getString("host")
      val user = rs.getString("user")
      println("host = %s, user = %s".format(host, user))
    }
  } catch {
    case e: Exception => e.printStackTrace
  }
  //關閉連接。釋放資源
  connection.close
}

3. Slick簡單介紹

在前一小節中我們演示了怎樣通過JDBC進行數據庫訪問。相同在Scala中也能夠利用JAVA中的ORM框架如Hibernate、IBatis等進行數據庫的操縱,但它們都是Java風格的數據庫操縱方式,Scala語言中也有著自己的ORM框架。眼下比較流行的框架包括:

1、Slick (typesafe公司開發)

2、Squeryl

3、Anorm

4、ScalaActiveRecord (基於Squeryl之上)

5、circumflex-orm

6、activate-framework(Scala版的Hibernate)

本節課程要講的便是Slick框架,它是Scala語言創建者所成立的公司TypeSafe所開發的一個Scala風格的開源數據庫操縱框架,它眼下支持以下幾種主流的數據:

DB2 (via slick-extensions)
Derby/JavaDB
H2
HSQLDB/HyperSQL
Microsoft Access
Microsoft SQL Server (via slick-extensions)
MySQL
Oracle (via slick-extensions)
PostgreSQL
SQLite

當然它也支持其他數據,僅僅只是功能可能還不完好。在Slick中。能夠像訪問Scala自身的集合一樣對數據庫進行操作。它具有例如以下幾個特點:

1 數據庫的訪問採用Scala風格:

//以下給出的是數據查詢操作
class Coffees(tag: Tag) extends Table[(String, Double)](tag, "COFFEES") {
  def name = column[String]("COF_NAME", O.PrimaryKey)
  def price = column[Double]("PRICE")
  def * = (name, price)
}
val coffees = TableQuery[Coffees]

//以下給出的數據訪問API
// Query that only returns the "name" column
coffees.map(_.name)

// Query that does a "where price < 10.0"
coffees.filter(_.price < 10.0)

從上面的代碼能夠看到。Slick訪問數據庫就跟Scala操縱自身的集合一樣.

2 Slick數據操縱是類型安全的

// The result of "select PRICE from COFFEES" is a Seq of Double
// because of the type safe column definitions
val coffeeNames: Seq[Double] = coffees.map(_.price).list

// Query builders are type safe:
coffees.filter(_.price < 10.0)
// Using a string in the filter would result in a compilation error

3 支持鏈式操作

// Create a query for coffee names with a price less than 10, sorted by name
coffees.filter(_.price < 10.0).sortBy(_.name).map(_.name)
// The generated SQL is equivalent to:
// select name from COFFEES where PRICE < 10.0 order by NAME

4. Slick 數據庫編程實戰

以下的代碼演示了Slick怎樣創建數據庫表、怎樣進行數據插入操作及怎樣進行數據的查詢操作(以MySQL為例):

package cn.scala.xtwy

//導入MySQL相關方法
import scala.slick.driver.MySQLDriver.simple._

object UseInvoker extends App {

  // 定義一個Test表
  //表中包括兩列,各自是id,name
  class Test(tag: Tag) extends Table[(Int, String)](tag, "Test") {
    def k = column[Int]("id", O.PrimaryKey)
    def v = column[String]("name")
     // Every table needs a * projection with the same type as the table‘s type parameter
     //每一個Table中都應該有*方法。它的類型必須與前面定義的類型參數(Int, String)一致
    def * = (k, v)
  }
  //創建TableQuery對象(這裏調用的是TableQuery的apply方法
  //沒有顯式地調用new 
  val ts = TableQuery[Test]

  //forURL註冊MySQL驅動器,傳入URL,用戶名及密碼
  //方法回返的是一個DatabaseDef對象,然後再調用withSession方法
  Database.forURL("jdbc:mysql://localhost:3306/slick", "root","123",
      driver = "com.mysql.jdbc.Driver") withSession { 

    //定義一個隱式值
    //implicit session: MySQLDriverbackend.Session
    //興許方法中當做隱式參數傳遞
    implicit session =>

    // 創建Test表
    //create方法中帶有一個隱式參數
    //def create(implicit session: JdbcBackend.SessionDef): Unit
    ts.ddl.create
    //插入數據
    //def insertAll(values: U*)(implicit session: JdbcBackend.SessionDef): MultiInsertResult
    ts.insertAll(1 -> "a", 2 -> "b", 3 -> "c", 4 -> "d", 5 -> "e")
   //數據庫查詢(這裏返回全部數據)
   ts.foreach { x => println("k="+x._1+" v="+x._2) }

   //這裏查詢返回全部主鍵 <3的
   ts.filter { _.k <3 }.foreach { x => println("k="+x._1+" v="+x._2) }
  }
  //模式匹配方式
  ts.foreach { case(id,name) => println("id="+id+" name="+name) }
}

以下我們再給一個更為復雜的樣例來演示Slick中是怎樣進行數據的入庫與查詢操作的:

package cn.scala.xtwy

import scala.slick.driver.MySQLDriver.simple._

object CoffeeExample extends App {
  // Definition of the SUPPLIERS table
  //定義Suppliers表
  class Suppliers(tag: Tag) extends Table[(Int, String, String, String, String, String)](tag, "SUPPLIERS") {
    def id = column[Int]("SUP_ID", O.PrimaryKey) // This is the primary key column
    def name = column[String]("SUP_NAME")
    def street = column[String]("STREET")
    def city = column[String]("CITY")
    def state = column[String]("STATE")
    def zip = column[String]("ZIP")
    // Every table needs a * projection with the same type as the table‘s type parameter
    def * = (id, name, street, city, state, zip)
  }
  val suppliers = TableQuery[Suppliers]

  // Definition of the COFFEES table
   //定義Coffees表
  class Coffees(tag: Tag) extends Table[(String, Int, Double, Int, Int)](tag, "COFFEES") {
    def name = column[String]("COF_NAME", O.PrimaryKey)
    def supID = column[Int]("SUP_ID")
    def price = column[Double]("PRICE")
    def sales = column[Int]("SALES")
    def total = column[Int]("TOTAL")
    def * = (name, supID, price, sales, total)
    // A reified foreign key relation that 
    //can be navigated to create a join
    //外鍵定義,它使得supID域中的值關聯到suppliers中的id
    //從而保證表中數據的正確性
    //它定義的事實上是一個n:1的關系,
    //即一個Coffees相應僅僅有一個Suppliers,
    //而一個Suppliers能夠相應多個Coffees
    def supplier = foreignKey("SUP_FK", supID, suppliers)(_.id)
  }
  val coffees = TableQuery[Coffees]

  Database.forURL("jdbc:mysql://localhost:3306/slick", "root", "123",
    driver = "com.mysql.jdbc.Driver") withSession {

      implicit session =>
        // Create the tables, including primary and foreign keys
        //按順序創建表
        (suppliers.ddl ++ coffees.ddl).create

        // Insert some suppliers
        //插入操作,集合的方式
        suppliers += (101, "Acme, Inc.", "99 Market Street", "Groundsville", "CA", "95199")
        suppliers += (49, "Superior Coffee", "1 Party Place", "Mendocino", "CA", "95460")
        suppliers += (150, "The High Ground", "100 Coffee Lane", "Meadows", "CA", "93966")

        // Insert some coffees (using JDBC‘s batch insert feature, if supported by the DB)
        //批量插入操作,集合方式
        coffees ++= Seq(
          ("Colombian", 101, 7.99, 0, 0),
          ("French_Roast", 49, 8.99, 0, 0),
          ("Espresso", 150, 9.99, 0, 0),
          ("Colombian_Decaf", 101, 8.99, 0, 0),
          ("French_Roast_Decaf", 49, 9.99, 0, 0))
       //返回表中全部數據,相當於SELECT * FROM COFFEES
       coffees foreach {
          case (name, supID, price, sales, total) =>
            println("  " + name + "\t" + supID + "\t" + price + "\t" + sales + "\t" + total)

        }
       //返回表中全部數據。僅僅只是這次是直接讓數據庫幫我們進行轉換
        val q1 = for (c <- coffees)
          yield LiteralColumn("  ") ++ c.name ++ "\t" ++ c.supID.asColumnOf[String] ++
          "\t" ++ c.price.asColumnOf[String] ++ "\t" ++ c.sales.asColumnOf[String] ++
          "\t" ++ c.total.asColumnOf[String]
        // The first string constant needs to be lifted manually to a LiteralColumn
        // so that the proper ++ operator is found
        q1 foreach println

        //聯合查詢
        //採用===進行比較操作,而非==操作符。用於進行值比較
        //相同的還有!=值不等比較符
        //甚至其他比較操作符與scala是一致的 <, <=, >=, >
         val q2 = for {
          c <- coffees if c.price < 9.0
          s <- suppliers if s.id === c.supID
        } yield (c.name, s.name)

}

5. SQL與Slick相互轉換

package cn.scala.xtwy

import scala.slick.driver.MySQLDriver.simple._
import scala.slick.jdbc.StaticQuery.interpolation
import scala.slick.jdbc.GetResult

object SQLAndSlick extends App {
  type Person = (Int, String, Int, Int)
  class People(tag: Tag) extends Table[Person](tag, "PERSON") {
    def id = column[Int]("ID", O.PrimaryKey)
    def name = column[String]("NAME")
    def age = column[Int]("AGE")
    def addressId = column[Int]("ADDRESS_ID")
    def * = (id, name, age, addressId)
    def address = foreignKey("ADDRESS", addressId, addresses)(_.id)
  }
  lazy val people = TableQuery[People]

  type Address = (Int, String, String)
  class Addresses(tag: Tag) extends Table[Address](tag, "ADDRESS") {
    def id = column[Int]("ID", O.PrimaryKey)
    def street = column[String]("STREET")
    def city = column[String]("CITY")
    def * = (id, street, city)
  }

  lazy val addresses = TableQuery[Addresses]

  val dbUrl = "jdbc:mysql://localhost:3306/slick"
  val jdbcDriver = "com.mysql.jdbc.Driver"
  val user = "root"
  val password = "123"
  val db = Database.forURL(dbUrl, user, password, driver = jdbcDriver)

  db.withSession { implicit session =>

    (people.ddl ++ addresses.ddl).create

    //插入address數據
    addresses += (23, "文一西路", "浙江省杭州市")
    addresses += (41, "紫荊花路", "浙江省杭州市")

    //插入people數據
    people += (1, "搖擺少年夢", 27, 23)
    people += (2, "john", 28, 41)
    people += (3, "stephen", 28, 23)

    //以下兩條語句是等同的(獲取固定幾個字段)
    val query = sql"select ID, NAME, AGE from PERSON".as[(Int, String, Int)]
    query.list.foreach(x => println("id=" + x._1 + " name=" + x._2 + " age=" + x._3))

    val query2 = people.map(p => (p.id, p.name, p.age))
    query2.list.foreach(x => println("id=" + x._1 + " name=" + x._2 + " age=" + x._3))

    //以下兩條語句是等同的(Where語句)
    val query3 = sql"select * from PERSON where AGE >= 18 AND NAME = ‘搖擺少年夢‘".as[Person]
    query3.list.foreach(x => println("id=" + x._1 + " name=" + x._2 + " age=" + x._3))

    val query4 = people.filter(p => p.age >= 18 && p.name === "搖擺少年夢")
    query4.list.foreach(x => println("id=" + x._1 + " name=" + x._2 + " age=" + x._3))

    //orderBy
    sql"select * from PERSON order by AGE asc, NAME".as[Person].list
    people.sortBy(p => (p.age.asc, p.name)).list

    //max
    sql"select max(AGE) from PERSON".as[Option[Int]].first
    people.map(_.age).max

    //隱式join
    sql"""
  select P.NAME, A.CITY
  from PERSON P, ADDRESS A
  where P.ADDRESS_ID = a.id
""".as[(String, String)].list

    people.flatMap(p =>
      addresses.filter(a => p.addressId === a.id)
        .map(a => (p.name, a.city))).run

    // or equivalent for-expression:
    (for (
      p <- people;
      a <- addresses if p.addressId === a.id
    ) yield (p.name, a.city)).run

    //join操作
    sql"""select P.NAME, A.CITY from PERSON P join ADDRESS A on P.ADDRESS_ID = a.id """.as[(String, String)].list
    (people join addresses on (_.addressId === _.id))
  .map{ case (p, a) => (p.name, a.city) }.run
  }

}

上面列出的僅僅是Slick與SQL的部分轉換,還有諸如:Update、Delete等操作能夠參見:http://slick.typesafe.com/doc/2.1.0/sql-to-slick.html

加入公眾微信號,能夠了解很多其他最新Spark、Scala相關技術資訊
技術分享

Scala入門到精通——第二十九節 Scala數據庫編程