這篇文章將為大家詳細講解有關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數據庫”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。