之前介绍了一些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
1group 'name.quanke.kotlin' 2version '1.0-SNAPSHOT' 3 4buildscript { 5 ext.kotlin_version = '1.2.10' 6 ext.spring_boot_version = '1.5.4.RELEASE' 7 ext.springfox_swagger2_version = '2.7.0' 8 ext.mysql_version = '5.1.21' 9 repositories { 10 mavenCentral() 11 } 12 dependencies { 13 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 14 classpath("org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version") 15 16// Kotlin整合SpringBoot的默认无参构造函数,默认把所有的类设置open类插件 17 classpath("org.jetbrains.kotlin:kotlin-noarg:$kotlin_version") 18 classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlin_version") 19 } 20} 21 22apply plugin: 'kotlin' 23apply plugin: "kotlin-spring" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin 24apply plugin: 'org.springframework.boot' 25 26jar { 27 baseName = 'chapter11-6-1-service' 28 version = '0.1.0' 29} 30repositories { 31 mavenCentral() 32} 33 34 35dependencies { 36 compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version" 37 compile "org.springframework.boot:spring-boot-starter-web:$spring_boot_version" 38 compile "org.springframework.boot:spring-boot-starter-jdbc:$spring_boot_version" 39 compile "mysql:mysql-connector-java:$mysql_version" 40 testCompile "org.springframework.boot:spring-boot-starter-test:$spring_boot_version" 41 testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version" 42 43} 44 45compileKotlin { 46 kotlinOptions.jvmTarget = "1.8" 47} 48compileTestKotlin { 49 kotlinOptions.jvmTarget = "1.8" 50}
在src/main/resources/application.yml中配置数据源信息
1spring: 2 datasource: 3 url: jdbc:mysql://localhost:3306/test 4 username: root 5 password: 123456 6 driver-class-name: com.mysql.jdbc.Driver 7
连接JNDI数据源
当你将应用部署于应用服务器上的时候想让数据源由应用服务器管理,那么可以使用如下配置方式引入JNDI数据源。
如果对JNDI不是很了解的,请参考 https://baike.baidu.com/item/JNDI/3792442?fr=aladdin
1spring.datasource.jndi-name=java:jboss/datasources/customers 2
使用JdbcTemplate操作数据库
Spring的JdbcTemplate是自动配置的,你可以直接使用@Autowired来注入到你自己的bean中来使用。
举例:我们在创建User表,包含属性id,name、age,下面来编写数据访问对象和单元测试用例。
定义包含有插入、删除、查询的抽象接口UserService
1interface UserService { 2 3 /** 4 * 获取用户总量 5 */ 6 val allUsers: Int? 7 8 /** 9 * 新增一个用户 10 * @param name 11 * @param age 12 */ 13 fun create(name: String, password: String?) 14 15 /** 16 * 根据name删除一个用户高 17 * @param name 18 */ 19 fun deleteByName(name: String) 20 21 /** 22 * 删除所有用户 23 */ 24 fun deleteAllUsers() 25 26}
通过JdbcTemplate实现UserService中定义的数据访问操作
1import org.springframework.beans.factory.annotation.Autowired 2import org.springframework.jdbc.core.JdbcTemplate 3import org.springframework.stereotype.Service 4/** 5 * Created by http://quanke.name on 2018/1/10. 6 */ 7@Service 8class UserServiceImpl : UserService { 9 10 @Autowired 11 private val jdbcTemplate: JdbcTemplate? = null 12 13 override val allUsers: Int? 14 get() = jdbcTemplate!!.queryForObject("select count(1) from USER", Int::class.java) 15 16 override fun create(name: String, password: String?) { 17 jdbcTemplate!!.update("insert into USER(USERNAME, PASSWORD) values(?, ?)", name, password) 18 } 19 20 override fun deleteByName(name: String) { 21 jdbcTemplate!!.update("delete from USER where USERNAME = ?", name) 22 } 23 24 override fun deleteAllUsers() { 25 jdbcTemplate!!.update("delete from USER") 26 } 27} 28
创建对UserService的单元测试用例,通过创建、删除和查询来验证数据库操作的正确性。
1/** 2 * Created by http://quanke.name on 2018/1/9. 3 */ 4@RunWith(SpringRunner::class) 5@SpringBootTest 6class ApplicationTests { 7 8 val log = LogFactory.getLog(ApplicationTests::class.java)!! 9 10 @Autowired 11 lateinit var userService: UserService 12 13 @Test 14 fun `jdbc test"`() { 15 16 val username = "quanke" 17 val password = "123456" 18 // 插入5个用户 19 userService.create("$username a", "$password 1") 20 userService.create("$username b", "$password 2") 21 userService.create("$username c", "$password 3") 22 userService.create("$username d", "$password 4") 23 userService.create("$username e", "$password 5") 24 25 26 log.info("总共用户 ${userService.allUsers}") 27 28 // 删除两个用户 29 userService.deleteByName("$username a") 30 userService.deleteByName("$username b") 31 32 log.info("总共用户 ${userService.allUsers}") 33 } 34 35}
上面介绍的JdbcTemplate只是最基本的几个操作,更多其他数据访问操作的使用请参考:JdbcTemplate API
通过上面这个简单的例子,我们可以看到在Spring Boot下访问数据库的配置依然秉承了框架的初衷:简单。我们只需要在pom.xml中加入数据库依赖,再到application.yml中配置连接信息,不需要像Spring应用中创建JdbcTemplate的Bean,就可以直接在自己的对象中注入使用。
更多Spring Boot 和 kotlin相关内容