之前介绍了一些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