Spring Boot 与 Kotlin 使用JdbcTemplate连接MySQL

Wesley13
• 阅读 558

之前介绍了一些Web层的例子,包括构建RESTful API、使用Thymeleaf模板引擎渲染Web视图,但是这些内容还不足以构建一个动态的应用。通常我们做App也好,做Web应用也好,都需要内容,而内容通常存储于各种类型的数据库,服务端在接收到访问请求之后需要访问数据库获取并处理成展现给用户使用的数据形式。

本文介绍在Spring Boot基础下配置数据源和通过JdbcTemplate编写数据访问的示例。

数据源配置

在我们访问数据库的时候,需要先配置一个数据源,下面分别介绍一下几种不同的数据库配置方式。

首先,为了连接数据库需要引入jdbc支持,在build.gradle中引入如下配置:

compile "org.springframework.boot:spring-boot-starter-jdbc:$spring_boot_version"

连接数据源

以MySQL数据库为例,先引入MySQL连接的依赖包,在build.gradle中加入:

compile "mysql:mysql-connector-java:$mysql_version"

完整build.gradle

group 'name.quanke.kotlin'
version '1.0-SNAPSHOT'

buildscript {
    ext.kotlin_version = '1.2.10'
    ext.spring_boot_version = '1.5.4.RELEASE'
    ext.springfox_swagger2_version = '2.7.0'
    ext.mysql_version = '5.1.21'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath("org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version")

//        Kotlin整合SpringBoot的默认无参构造函数,默认把所有的类设置open类插件
        classpath("org.jetbrains.kotlin:kotlin-noarg:$kotlin_version")
        classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlin_version")
    }
}

apply plugin: 'kotlin'
apply plugin: "kotlin-spring" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin
apply plugin: 'org.springframework.boot'

jar {
    baseName = 'chapter11-6-1-service'
    version = '0.1.0'
}
repositories {
    mavenCentral()
}


dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    compile "org.springframework.boot:spring-boot-starter-web:$spring_boot_version"
    compile "org.springframework.boot:spring-boot-starter-jdbc:$spring_boot_version"
    compile "mysql:mysql-connector-java:$mysql_version"
    testCompile "org.springframework.boot:spring-boot-starter-test:$spring_boot_version"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"

}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

src/main/resources/application.yml中配置数据源信息

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver

连接JNDI数据源

当你将应用部署于应用服务器上的时候想让数据源由应用服务器管理,那么可以使用如下配置方式引入JNDI数据源。

如果对JNDI不是很了解的,请参考 https://baike.baidu.com/item/JNDI/3792442?fr=aladdin

spring.datasource.jndi-name=java:jboss/datasources/customers

使用JdbcTemplate操作数据库

Spring的JdbcTemplate是自动配置的,你可以直接使用@Autowired来注入到你自己的bean中来使用。

举例:我们在创建User表,包含属性id,name、age,下面来编写数据访问对象和单元测试用例。

定义包含有插入、删除、查询的抽象接口UserService

interface UserService {

    /**
     * 获取用户总量
     */
    val allUsers: Int?

    /**
     * 新增一个用户
     * @param name
     * @param age
     */
    fun create(name: String, password: String?)

    /**
     * 根据name删除一个用户高
     * @param name
     */
    fun deleteByName(name: String)

    /**
     * 删除所有用户
     */
    fun deleteAllUsers()

}

通过JdbcTemplate实现UserService中定义的数据访问操作

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.stereotype.Service
/**
 * Created by http://quanke.name on 2018/1/10.
 */
@Service
class UserServiceImpl : UserService {

    @Autowired
    private val jdbcTemplate: JdbcTemplate? = null

    override val allUsers: Int?
        get() = jdbcTemplate!!.queryForObject("select count(1) from USER", Int::class.java)

    override fun create(name: String, password: String?) {
        jdbcTemplate!!.update("insert into USER(USERNAME, PASSWORD) values(?, ?)", name, password)
    }

    override fun deleteByName(name: String) {
        jdbcTemplate!!.update("delete from USER where USERNAME = ?", name)
    }

    override fun deleteAllUsers() {
        jdbcTemplate!!.update("delete from USER")
    }
}

创建对UserService的单元测试用例,通过创建、删除和查询来验证数据库操作的正确性。

/**
 * Created by http://quanke.name on 2018/1/9.
 */
@RunWith(SpringRunner::class)
@SpringBootTest
class ApplicationTests {

    val log = LogFactory.getLog(ApplicationTests::class.java)!!

    @Autowired
    lateinit var userService: UserService

    @Test
    fun `jdbc test"`() {

        val username = "quanke"
        val password = "123456"
        // 插入5个用户
        userService.create("$username a", "$password 1")
        userService.create("$username b", "$password 2")
        userService.create("$username c", "$password 3")
        userService.create("$username d", "$password 4")
        userService.create("$username e", "$password 5")


        log.info("总共用户 ${userService.allUsers}")

        // 删除两个用户
        userService.deleteByName("$username a")
        userService.deleteByName("$username b")

        log.info("总共用户 ${userService.allUsers}")
    }

}

上面介绍的JdbcTemplate只是最基本的几个操作,更多其他数据访问操作的使用请参考:JdbcTemplate API

通过上面这个简单的例子,我们可以看到在Spring Boot下访问数据库的配置依然秉承了框架的初衷:简单。我们只需要在pom.xml中加入数据库依赖,再到application.yml中配置连接信息,不需要像Spring应用中创建JdbcTemplate的Bean,就可以直接在自己的对象中注入使用。

更多Spring Boot 和 kotlin相关内容

欢迎关注《Spring Boot 与 kotlin 实战》 Spring Boot 与 Kotlin 使用JdbcTemplate连接MySQL

参考

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这