Spring Boot 与 Kotlin 使用JdbcTemplate连接MySQL数据库的方法
之前介绍了一些Web层的例子,包括构建RESTfulAPI、使用Thymeleaf模板引擎渲染Web视图,但是这些内容还不足以构建一个动态的应用。通常我们做App也好,做Web应用也好,都需要内容,而内容通常存储于各种类型的数据库,服务端在接收到访问请求之后需要访问数据库获取并处理成展现给用户使用的数据形式。
本文介绍在SpringBoot基础下配置数据源和通过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") } } applyplugin:'kotlin' applyplugin:"kotlin-spring"//Seehttps://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin applyplugin:'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
interfaceUserService{ /** *获取用户总量 */ valallUsers:Int? /** *新增一个用户 *@paramname *@paramage */ funcreate(name:String,password:String?) /** *根据name删除一个用户高 *@paramname */ fundeleteByName(name:String) /** *删除所有用户 */ fundeleteAllUsers() }
通过JdbcTemplate实现UserService中定义的数据访问操作
importorg.springframework.beans.factory.annotation.Autowired importorg.springframework.jdbc.core.JdbcTemplate importorg.springframework.stereotype.Service /** *Createdbyhttp://quanke.nameon2018/1/10. */ @Service classUserServiceImpl:UserService{ @Autowired privatevaljdbcTemplate:JdbcTemplate?=null overridevalallUsers:Int? get()=jdbcTemplate!!.queryForObject("selectcount(1)fromUSER",Int::class.java) overridefuncreate(name:String,password:String?){ jdbcTemplate!!.update("insertintoUSER(USERNAME,PASSWORD)values(?,?)",name,password) } overridefundeleteByName(name:String){ jdbcTemplate!!.update("deletefromUSERwhereUSERNAME=?",name) } overridefundeleteAllUsers(){ jdbcTemplate!!.update("deletefromUSER") } }
创建对UserService的单元测试用例,通过创建、删除和查询来验证数据库操作的正确性。
/** *Createdbyhttp://quanke.nameon2018/1/9. */ @RunWith(SpringRunner::class) @SpringBootTest classApplicationTests{ vallog=LogFactory.getLog(ApplicationTests::class.java)!! @Autowired lateinitvaruserService:UserService @Test fun`jdbctest"`(){ valusername="quanke" valpassword="123456" //插入5个用户 userService.create("$usernamea","$password1") userService.create("$usernameb","$password2") userService.create("$usernamec","$password3") userService.create("$usernamed","$password4") userService.create("$usernamee","$password5") log.info("总共用户${userService.allUsers}") //删除两个用户 userService.deleteByName("$usernamea") userService.deleteByName("$usernameb") log.info("总共用户${userService.allUsers}") } }
上面介绍的JdbcTemplate只是最基本的几个操作,更多其他数据访问操作的使用请参考:JdbcTemplateAPI
通过上面这个简单的例子,我们可以看到在SpringBoot下访问数据库的配置依然秉承了框架的初衷:简单。我们只需要在pom.xml中加入数据库依赖,再到application.yml中配置连接信息,不需要像Spring应用中创建JdbcTemplate的Bean,就可以直接在自己的对象中注入使用。
总结
以上所述是小编给大家介绍的SpringBoot与Kotlin使用JdbcTemplate连接MySQL数据库的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!