官网地址:http://scalikejdbc.org/
参考官网:
添加maven依赖:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.28</version>
</dependency>
<dependency>
<groupId>org.scalikejdbc</groupId>
<!-- 此处版本号config_2.11一定要和代码中编译scala的版本号一致 -->
<artifactId>scalikejdbc-config_2.11</artifactId>
<version>2.5.2</version>
</dependency>
在项目中的 src/main/resources/ 目录下创建文件 application.conf,拷贝如下代码到文件中:
# JDBC settings
db.default.driver="com.mysql.jdbc.Driver"
db.default.url="jdbc:mysql://master:3306/test_db" //填写自己的数据库地址
db.default.user="root" // 用户名
db.default.password="123456" // 密码
# Connection Pool settings
db.default.poolInitialSize=10
db.default.poolMaxSize=20
db.default.connectionTimeoutMillis=1000
示例代码:
import scalikejdbc.{DB, SQL}
import scalikejdbc.config.DBs
object ScalikeJDBCApp {
def insert(): Unit = {
DB.autoCommit({
implicit session => {
SQL("insert into offset_table (topic, groupid, partitions, offset) values(?,?,?,?)")
.bind("ts", "group", 3, 8)
.update().apply()
}
})
}
def update(): Unit = {
DB.autoCommit({
implicit session => {
SQL("update offset_table set offset=? where topic=? and groupid=? and partitions=?")
.bind(18, "ts", "group", 3)
.update().apply()
}
})
}
def query(): Unit = {
val offsets = DB.readOnly({
implicit session => {
SQL("SELECT * FROM offset_table").map(rs => {
Offset(
rs.string("topic"),
rs.string("groupid"),
rs.int("partitions"),
rs.long("offset")
)
}).list().apply()
}
})
offsets.foreach(println)
}
def delete(): Unit = {
DB.autoCommit({
implicit session => {
SQL("delete from offset_table where partitions=?")
.bind(3)
.update().apply()
}
})
}
def transaction(): Unit = {
DB.localTx({
implicit session => {
SQL("delete from offset_table where partitions=?")
.bind(2)
.update().apply()
//1/0
SQL("delete from offset_table where partitions=?")
.bind(1)
.update().apply()
}
})
}
def main(args: Array[String]): Unit = {
DBs.setupAll() // 解析配置文件
insert() // 插入
update() // 更新
query() // 查询
delete() // 删除
transaction()// 事务
}
}
case class Offset(topic: String, groupId: String, partitionId: Int, offset: Long)