用Kotlin寫一個基於Spring Boot的RESTful服務


Spring太復雜了,配置這個東西簡直就是浪費生命。尤其在沒有什么並發壓力,隨便搞一個RESTful服務
讓整個業務跑起來先的情況下,更是么有必要糾結在一堆的XML配置上。顯然這么想的人是很多的,於是就
有了Spring Boot。又由於Java 8太墨跡於是有了Kotlin。

數據源使用MySql。通過Spring Boot這個基本不怎么配置的,不怎么微的微框架的Spring Data JPA和Hibernate
來訪問數據。

處理依賴

這里使用Gradle來處理依賴。

  • 首先下載官網給的初始項目:
git clone https://github.com/spring-guides/gs-accessing-data-jpa.git
  • 然后跳轉到gs-accessing-data-jpa/initial目錄下。
  • 用IntelliJ IDEA打開這個項目,選擇使用Gradle管理依賴。

之后Gradle會自動下載依賴項。這會花一點時間。你可以去和妹子聊一會兒了。。

如果你覺得這樣很麻煩的話,可以建立一個Gradle項目。之后根據上面的例子建立一個目錄:

└── src
    └── main
        └── java
            └── hello

但是無論是用上面的哪種方式,最后都需要在Gradle文件中添加依賴項。這個Gradle文件是build.gradle。添加完依賴項
之后是這樣的:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.3.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'gs-spring-boot'
    version = '0.1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    // tag::jetty[]
    compile("org.springframework.boot:spring-boot-starter-web") {
        exclude module: "spring-boot-starter-tomcat"
    }
    compile("org.springframework.boot:spring-boot-starter-jetty")
    // end::jetty[]
    // tag::actuator[]
    compile("org.springframework.boot:spring-boot-starter-actuator")
    // end::actuator[]
    compile('org.springframework.boot:spring-boot-starter-data-jpa:1.3.3.RELEASE')

    compile('mysql:mysql-connector-java:5.1.13')

    testCompile("junit:junit")
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.3'
}

配置文件

在目錄src/main/resources/application.properties下編輯配置文件。默認是沒有這個文件和相應的目錄的,
自行創建。

spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root
#spring.datasource.driverClassName = com.mysql.jdbc.Driver

# Specify the DBMS
spring.jpa.database = MYSQL

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

無需java的配置類,或者什么XML配置文件。

使用配置項hibernate.ddl-auto = true,項目所需的數據庫和相關表、列會自動根據定義的實體類創建。點擊
這里
查看更多配置的說明。

創建一個簡單地實體類

這里定義一個簡單地實體類,並聲明為JPA實體。這個類的文件存放在目錄src\main\java\hello\Entities\下。

package hello.Entities

import javax.validation.constraints.NotNull
import java.io.Serializable;
import javax.persistence.*;

/**
 * Created by Bruce on 2016/3/9.
 */
@Entity
@Table(name = "user")
data class User(@Id @GeneratedValue(strategy = GenerationType.AUTO) var id: Long? = 0,
                @Column(nullable = false) var name: String? = null,
                @Column(nullable = false) var email: String? = null) : Serializable {

    protected constructor() : this(id = null, name = null, email = null) {
    }
}

這里使用了Kotlin里的data class。data class最大的優點就是省去了定義getter和setter,以及toString()
的時間。這些都已經默認實現。所以,在使用data class的對象的時候直接可以使用nameemail當然還有id這樣的屬性直接訪問。

無參數的構造函數是給JPA用的,所以訪問級別設定為protected。主構造函數是用來創建和數據庫操作相關的對象的。

整個的整個類被@Entity修飾,說明整個類是一個JPA的實體類。@Table聲明用來表明整個類對應的數據庫表是哪一個。
@Id修飾的User的屬性id,會被JPA認為的對象的ID。同時@GeneratedValue(strategy = GenerationType.AUTO)
的修飾說明這個ID是自動生成的。

另外的兩個屬性nameemail@Column(nullable = false)修飾。說明兩個列都是不可以為空的,同時說明兩個列的名字
和屬性的名字是相同的。如果不同可以這樣@Column(nullable = false, name="XXXXXX")

創建簡單地查詢,或者說Dao類

這個就更加的簡單了。JPA會自動在運行時創建數據庫需要的增刪改查的實現。這個實現可以是根據我們給出的Repository
來實現的。

根據User類,我們來實現一個UserDao(Repository):

package hello.Entities

import org.springframework.data.repository.CrudRepository
import org.springframework.transaction.annotation.Transactional

@Transactional
interface UserDao : CrudRepository<User, Long> {
    fun findByEmail(email: String): User?
}

泛型的類型參數分別是user和user的id的類型:User, Long。我們可以定義增刪改查之外的Query。比如在上面的代碼里
我們定義了一個findByEmail()方法。具體的自定義查詢時的命名規則可以查看這里

用Controller測試一下

數據庫,Rest服務和書庫的連接都已經搞定。那么,我們就來測試一下。

我們在目錄src\main\java\hello\Controllers創建一個UserController類來測試和數據庫的數據存取。

package hello.Controllers

import hello.Entities.User
import hello.Entities.UserDao
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody

/**
 * Created by Bruce on 2016/3/9.
 */

@RestController
class UserController {
    @Autowired
    private var userDao: UserDao? = null

    @RequestMapping("/create")
    @ResponseBody
    public fun create(name: String, email: String): User? {
        try {
            var newUser = User(name = name, email = email)
            userDao?.save(newUser)

            return newUser
        } catch(e: Exception) {
            return null
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    public fun delete(id: Long): String {
        try {
            var user = User(id)
            userDao?.delete(user)

            return id.toString() + "deleted"
        } catch(e: Exception) {
            return "delete error " + e.message.toString()
        }
    }

    @RequestMapping("/get-by-email")
    @ResponseBody
    public fun getByEmail(email: String): User? {
        try {
            var user = userDao?.findByEmail(email)
            if (user != null) {
                return user
            } else {
                return null
            }
        } catch(e: Exception) {
            return null
        }
    }

    @RequestMapping("/update")
    @ResponseBody
    public fun updateUser(id: Long, name: String, email: String): User? {
        try {
            var user: User? = userDao?.findOne(id) ?: return null

            user?.name = name
            user?.email = email
            userDao?.save(user)

            return user
        } catch(e: Exception) {
            return null
        }
    }
}

測試URL可以是這樣的:

  • /create?name=Jack&email=hello@234.com,使用指定的用戶名和郵箱在數據庫里生成一個新的user,id是自動生成的。
  • /delete?id=3, 刪除id值為3的user。
  • /get-by-email?email=hello@234.com,注意Controller用到的UserDao.findByEmail()只返回一個user,所以如果有多個
    返回值的話會報錯。
  • /update?id=1&email=what@123.com&name=Bruce,更新id為1的user。

代碼在這里

參考文章:
http://blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/
https://spring.io/guides/gs/accessing-data-jpa/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM