当前位置: 首页 > 工具软件 > Scala Slick > 使用案例 >

scala使用slick操作mysql数据库

李和昶
2023-12-01

1.pom文件

<dependency>
    <groupId>com.typesafe.slick</groupId>
    <artifactId>slick_2.10</artifactId>
    <version>3.1.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.27</version>
</dependency>

2.建表

CREATE TABLE `Person`(
`id` VARCHAR(20),
`name` VARCHAR(20) NOT NULL DEFAULT '',
`birth` INT(20) NOT NULL DEFAULT 0,
`sex` VARCHAR(10) NOT NULL DEFAULT '',
`heigh` INT(20) ,
PRIMARY KEY(`id`)
);

3.配置application.conf

mip_common = {
  url = "jdbc:mysql://localhost:3306/test"
  driver = com.mysql.jdbc.Driver
  user = "root"
  password = "123456"
  connectionPool = disabled
  keepAliveConnection = true
}

4.model

package com.cn

import slick.driver.MySQLDriver.api._

//表字段对应模版
case class Person(id: String = "1",
                  name: String = null,
                  birth: Long = 0,
                  sex: String = null,
                  heigh: Option[Long] = Some(0)
                 )

object Person {
  //表结构: 定义字段类型, * 代表结果集字段
  class T(tag: Tag) extends Table[Person](tag, "Person") {
    def id = column[String]("id")

    def name = column[String]("name")

    def birth = column[Long]("birth")

    def sex = column[String]("sex")

    def heigh = column[Option[Long]]("heigh")

    def * = (id, name, birth, sex, heigh) <> ((Person.apply _).tupled, Person.unapply)

  }

  //库表实例
  val q = TableQuery[T]
}

5.dao

package com.cn

import slick.driver.MySQLDriver.api._
import scala.concurrent.Await
import scala.concurrent.duration.Duration



trait AbstractDao {
  val db = Database.forConfig(getConfigName)

  def getConfigName: String

  implicit def run[T](todo: DBIOAction[T, NoStream, Nothing]): T = Await.result(db.run(todo), Duration.Inf)
}

trait CommonAbstractDao extends AbstractDao {
  override def getConfigName: String = "mip_common"
}

object PersonDao extends CommonAbstractDao {
  //  增
  def insertPerson(conf:Person):Int={
    Person.q+=conf
  }
  
  //  改
  def updateHeighById(id:String,heigh:Option[Long]):Int={
    Person.q
      .filter(_.id===id)
      .map(r=>(r.heigh))
      .update(heigh)
  }
  
  // 查
  def selectPersonById(id: String): Person = {
    Person.q
      .filter(_.id === id)
      .map(r => r)
      .result
      .head
  }

  // 处理查询不存在的异常
  def selectSexById(id: String): (String,String) = {
    val resultSet=Person.q
      .filter(_.id === id)
      .map(r => (r.name,r.sex))
      .result
    if (resultSet.nonEmpty){
      resultSet.head
    }else{
      ("nothing","")
    }
  }

  def main(args: Array[String]): Unit = {
    val p = selectPersonById("1")
    println(p)

  }
}

 类似资料: