日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

用Kotlin写一个基于Spring Boot的RESTful服务

發(fā)布時間:2025/3/21 javascript 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用Kotlin写一个基于Spring Boot的RESTful服务 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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

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

處理依賴

這里使用Gradle來處理依賴。

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

    git clone https://github.com/spring-guides/gs-accessing-data-jpa.git
  • 然后跳轉(zhuǎn)到gs-accessing-data-jpa/initial目錄下。
  • 用IntelliJ IDEA打開這個項目,選擇使用Gradle管理依賴。

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

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

└── 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.8dependencies {// 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下編輯配置文件。默認是沒有這個文件和相應(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配置文件。

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

創(chuàng)建一個簡單地實體類

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

package hello.Entitiesimport 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)點就是省去了定義getter和setter,以及toString()
的時間。這些都已經(jīng)默認實現(xiàn)。所以,在使用data class的對象的時候直接可以使用name、email當然還有id這樣的屬性直接訪問。

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

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

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

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

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

根據(jù)User類,我們來實現(xiàn)一個UserDao(Repository):

package hello.Entitiesimport org.springframework.data.repository.CrudRepository import org.springframework.transaction.annotation.Transactional@Transactional interface UserDao : CrudRepository<User, Long> {fun findByEmail(email: String): User? }

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

用Controller測試一下

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

我們在目錄src\main\java\hello\Controllers創(chuàng)建一個UserController類來測試和數(shù)據(jù)庫的數(shù)據(jù)存取。

package hello.Controllersimport 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 {@Autowiredprivate var userDao: UserDao? = null@RequestMapping("/create")@ResponseBodypublic 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")@ResponseBodypublic 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")@ResponseBodypublic 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")@ResponseBodypublic fun updateUser(id: Long, name: String, email: String): User? {try {var user: User? = userDao?.findOne(id) ?: return nulluser?.name = nameuser?.email = emailuserDao?.save(user)return user} catch(e: Exception) {return null}} }

測試URL可以是這樣的:

  • /create?name=Jack&email=hello@234.com,使用指定的用戶名和郵箱在數(shù)據(jù)庫里生成一個新的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/

總結(jié)

以上是生活随笔為你收集整理的用Kotlin写一个基于Spring Boot的RESTful服务的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。