温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring Boot与Kotlin怎么使用JdbcTemplate连接MySQL数据库

发布时间:2021-06-18 09:55:18 来源:亿速云 阅读:169 作者:小新 栏目:编程语言

这篇文章将为大家详细讲解有关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数据库”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI