溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

在Kotlin中使用Spring Boot怎么實(shí)現(xiàn)一個(gè)RESTful服務(wù)

發(fā)布時(shí)間:2020-11-20 15:18:55 來源:億速云 閱讀:178 作者:Leah 欄目:編程語言

今天就跟大家聊聊有關(guān)在Kotlin中使用Spring Boot怎么實(shí)現(xiàn)一個(gè)RESTful服務(wù),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

Spring太復(fù)雜了,配置這個(gè)東西簡(jiǎn)直就是浪費(fèi)生命。尤其在沒有什么并發(fā)壓力,隨便搞一個(gè)RESTful服務(wù),讓整個(gè)業(yè)務(wù)跑起來先的情況下,更是么有必要糾結(jié)在一堆的XML配置上。顯然這么想的人是很多的,于是就有了Spring Boot。又由于Java 8太墨跡于是有了Kotlin。

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

處理依賴

這里使用Gradle來處理依賴。

首先下載官網(wǎng)給的初始項(xiàng)目:

git clone https://github.com/spring-guides/gs-accessing-data-jpa.git

然后跳轉(zhuǎn)到gs-accessing-data-jpa/initial目錄下。

用IntelliJ IDEA打開這個(gè)項(xiàng)目,選擇使用Gradle管理依賴。

之后Gradle會(huì)自動(dòng)下載依賴項(xiàng)。這會(huì)花一點(diǎn)時(shí)間。你可以去和妹子聊一會(huì)兒了。。

如果你覺得這樣很麻煩的話,可以建立一個(gè)Gradle項(xiàng)目。之后根據(jù)上面的例子建立一個(gè)目錄:

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

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

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下編輯配置文件。默認(rèn)是沒有這個(gè)文件和相應(yīng)的目錄的,自行創(chuàng)建。

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配置文件。

使用配置項(xiàng)hibernate.ddl-auto = true,項(xiàng)目所需的數(shù)據(jù)庫(kù)和相關(guān)表、列會(huì)自動(dòng)根據(jù)定義的實(shí)體類創(chuàng)建。點(diǎn)擊這里,查看更多配置的說明。

創(chuàng)建一個(gè)簡(jiǎn)單地實(shí)體類

這里定義一個(gè)簡(jiǎn)單地實(shí)體類,并聲明為JPA實(shí)體。這個(gè)類的文件存放在目錄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最大的優(yōu)點(diǎn)就是省去了定義getter和setter,以及toString()的時(shí)間。這些都已經(jīng)默認(rèn)實(shí)現(xiàn)。所以,在使用data class的對(duì)象的時(shí)候直接可以使用nameemail當(dāng)然還有id這樣的屬性直接訪問。

無參數(shù)的構(gòu)造函數(shù)是給JPA用的,所以訪問級(jí)別設(shè)定為protected。主構(gòu)造函數(shù)是用來創(chuàng)建和數(shù)據(jù)庫(kù)操作相關(guān)的對(duì)象的。

整個(gè)的整個(gè)類被@Entity修飾,說明整個(gè)類是一個(gè)JPA的實(shí)體類。@Table聲明用來表明整個(gè)類對(duì)應(yīng)的數(shù)據(jù)庫(kù)表是哪一個(gè)。
@Id修飾的User的屬性id,會(huì)被JPA認(rèn)為的對(duì)象的ID。同時(shí)@GeneratedValue(strategy = GenerationType.AUTO)
的修飾說明這個(gè)ID是自動(dòng)生成的。

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

創(chuàng)建簡(jiǎn)單地查詢,或者說Dao類

這個(gè)就更加的簡(jiǎn)單了。JPA會(huì)自動(dòng)在運(yùn)行時(shí)創(chuàng)建數(shù)據(jù)庫(kù)需要的增刪改查的實(shí)現(xiàn)。這個(gè)實(shí)現(xiàn)可以是根據(jù)我們給出的Repository
來實(shí)現(xiàn)的。

根據(jù)User類,我們來實(shí)現(xiàn)一個(gè)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&#63;
}

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

用Controller測(cè)試一下

數(shù)據(jù)庫(kù),Rest服務(wù)和書庫(kù)的連接都已經(jīng)搞定。那么,我們就來測(cè)試一下。

我們?cè)谀夸?code>src\main\java\hello\Controllers創(chuàng)建一個(gè)UserController類來測(cè)試和數(shù)據(jù)庫(kù)的數(shù)據(jù)存取。

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&#63; = null

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

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

  @RequestMapping("/delete")
  @ResponseBody
  public fun delete(id: Long): String {
    try {
      var user = User(id)
      userDao&#63;.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&#63; {
    try {
      var user = userDao&#63;.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&#63; {
    try {
      var user: User&#63; = userDao&#63;.findOne(id) &#63;: return null

      user&#63;.name = name
      user&#63;.email = email
      userDao&#63;.save(user)

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

測(cè)試URL可以是這樣的:

  1. /create&#63;name=Jack&email=hello@234.com,使用指定的用戶名和郵箱在數(shù)據(jù)庫(kù)里生成一個(gè)新的user,id是自動(dòng)生成的。
  2. /delete&#63;id=3, 刪除id值為3的user。
  3. /get-by-email&#63;email=hello@234.com,注意Controller用到的UserDao.findByEmail()只返回一個(gè)user,所以如果有多個(gè) 返回值的話會(huì)報(bào)錯(cuò)。
  4. /update&#63;id=1&email=what@123.com&name=Bruce,更新id為1的user。

看完上述內(nèi)容,你們對(duì)在Kotlin中使用Spring Boot怎么實(shí)現(xiàn)一個(gè)RESTful服務(wù)有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI