可能是最好的Scala持久层库ScalikeJDBC

Scala中好用的持久层框架不多,虽然也可以使用传统Java中的MyBatis、Hibernate等框架,但又感觉又不够Scala。这种情况下ScalikeJDBC就是一个非常好的选择:文档详细,代码干净。PS:很多Scala项目文档都不够好。

使用方法:在sbt配置中添加

libraryDependencies ++= Seq(  
    "org.scalikejdbc" %% "scalikejdbc" % "2.2.0",
    "mysql" % "mysql-connector-java" % "5.1.21",
    "ch.qos.logback" % "logback-classic" % "1.1.2"
)

ScalikeJDBC可以很好的支持DDD形式的Domain Object

import scalikejdbc._  
case class Person(id: Long, name: String, address: Option[String]) {  
    def create = Person.create(this)
    def modify = Person.modify(this)
    def remove = Person.remove(this)
}

object Person extends SQLSyntaxSupport[Person] {  
    implicit val session = AutoSession
    val p = Person.syntax("p")

    def apply(rs: WrappedResultSet) = new Person(
        rs.long("id"), 
        rs.string("name"), 
        rs.stringOpt("address")
    )

    def get(id: Long): Option[Person] = withSQL {
        select.from(Person as p).where.eq(p.id, id)
    }.map(rs => Person(rs)).single.apply

    def create(obj: Person): Person = {
        val id = withSQL {
            insert.into(Person).namedValues(
                column.name -> obj.name,
                column.address -> obj.address
            )
        }.updateAndReturnGeneratedKey.apply
        Person(id = id, name = obj.name, address = obj.address)
    }

    def modify(obj: Person): Long = withSQL {
        update(Person).set(
            p.name -> obj.name,
            p.address -> obj.address
        ).where.eq(p.id, obj.id)  
    }.update.apply

    def remove(id: Long): Long = withSQL {
        delete.from(Person as a).where.eq(a.id, id)
    }.update.apply
}

使用scalikejdbc-config配置数据库连接

// build.sbt
libraryDependencies ++= Seq(  
    "org.scalikejdbc" %% "scalikejdbc-config" % "2.2.0"
)

// src/main/resources/application.conf
# MySQL example
db.default.driver="com.mysql.jdbc.Driver"  
db.default.url="jdbc:mysql://localhost:3306/example"  
db.default.user="test"  
db.default.password="test"  
# Connection Pool settings
db.default.poolInitialSize=10  
db.default.poolMaxSize=20  
db.default.connectionTimeoutMillis=1000  
db.default.poolInitialSize=5  
db.default.poolMaxSize=7  
db.default.poolConnectionTimeoutMillis=1000  
db.default.poolValidationQuery="select 1 as one"  
db.default.poolFactoryName="commons-dbcp"

// scala code
import scalikejdbc._  
import scalikejdbc.config._

DBs.setupAll // 初始化数据库  
val person = Person.get(1)  
DBs.closeAll  

ohfree9

继续阅读此作者的更多文章