kotlin mysql数据库_Spring Boot 与 Kotlin 使用JdbcTemplate连接MySQL数据库的方法

之前介绍了一些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 使用JdbcTemplate连接MySQL数据库的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

本文标题: Spring Boot 与 Kotlin 使用JdbcTemplate连接MySQL数据库的方法

本文地址: http://www.cppcns.com/ruanjian/java/218290.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值