之前介绍了一些Web层的例子,包括构建RESTful API、使用Thymeleaf模板引擎渲染Web视图,但是这些内容还不足以构建一个动态的应用。通常我们做App也好,做Web应用也好,都需要内容,而内容通常存储于各种类型的数据库,服务端在接收到访问请求之后需要访问数据库获取并处理成展现给用户使用的数据形式。
本文介绍在Spring Boot基础下配置数据源和通过 JdbcTemplate 编写数据访问的示例。
数据源配置
在我们访问数据库的时候,需要先配置一个数据源,下面分别介绍一下几种不同的数据库配置方式。
首先,为了连接数据库需要引入jdbc支持,在 build.gradle 中引入如下配置:
|
1
|
compile "org.springframework.boot:spring-boot-starter-jdbc:$spring_boot_version"
|
连接数据源
以MySQL数据库为例,先引入MySQL连接的依赖包,在 build.gradle 中加入:
|
1
|
compile "mysql:mysql-connector-java:$mysql_version"
|
完整 build.gradle
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
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 中配置数据源信息
|
1
2
3
4
5
6
|
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
|
1
|
spring.datasource.jndi-name=java:jboss/datasources/customers
|
使用JdbcTemplate操作数据库
Spring的 JdbcTemplate 是自动配置的,你可以直接使用 @Autowired 来注入到你自己的bean中来使用。
举例:我们在创建 User 表,包含属性id,name、age,下面来编写数据访问对象和单元测试用例。
定义包含有插入、删除、查询的抽象接口UserService
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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 中定义的数据访问操作
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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的单元测试用例,通过创建、删除和查询来验证数据库操作的正确性。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
/**
* 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数据库的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!
原文链接:https://www.jianshu.com/p/e5af6692f086
相关文章
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
-
2025-05-29 58
-
Xshell实现Windows上传文件到Linux主机的方法
2025-05-25 66 -
php array_walk array_map array_filter区别案例详解
2025-05-29 24 -
2025-05-27 52
-
2025-05-25 72

