前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot与Kotlin使用Spring Data Rest创建HAL风格Restful接口

Spring Boot与Kotlin使用Spring Data Rest创建HAL风格Restful接口

作者头像
全科
发布2018-08-15 11:05:01
7860
发布2018-08-15 11:05:01
举报
文章被收录于专栏:全栈架构全栈架构

REST web服务已成为在web上应用程序集成的首选方式。在其核心中,REST定义了系统由客户端交互的资源组成。这些资源以超媒体驱动的方式实现。Spring MVC为构建这些服务提供了坚实的基础。但是,对于多域对象系统,即使实施REST web服务的最简单原则也可能相当乏味,并且导致大量样板代码。

Spring Data REST构建在Spring Data repositories之上,并自动将其导出为REST资源。它利用超媒体来允许客户端查找存储库暴露的功能,并将这些资源自动集成到相关的超媒体功能中。

  • 根据model,生成HAL风格的restful API
  • 根据model,维护实体之间的关系
  • 支持分页
  • 允许动态地过滤集合资源
  • 允许通过处理Spring ApplicationEvents处理REST请求。
  • 目前支持JPA,MongoDB,Neo4j,Solr,Cassandra,Gemfire。
  • 支持自定义

将Spring Data REST添加到Spring Boot项目

代码语言:javascript
复制
dependencies {
    ...
    compile "org.springframework.boot:spring-boot-starter-data-rest:$spring_boot_version"
    ...
}

完整的 build.gradle文件

代码语言:javascript
复制
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'
    ext.mybatis_version = '1.1.1'
    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'
apply plugin: "kotlin-jpa"  //https://stackoverflow.com/questions/32038177/kotlin-with-jpa-default-constructor-hell
jar {
    baseName = 'chapter11-6-7-service'
    version = '0.1.0'
}
repositories {
    mavenCentral()
}


dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    compile("org.jetbrains.kotlin:kotlin-reflect:${kotlin_version}")

    compile "org.springframework.boot:spring-boot-starter-data-jpa:$spring_boot_version"
    compile "org.springframework.boot:spring-boot-starter-data-rest:$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"
}

创建对象User

代码语言:javascript
复制
import javax.persistence.*

/**
 * Created by http://quanke.name on 2018/1/10.
 */

@Entity
data class User(
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        var id: Long = -1,
        @Column(nullable = false)
        var username: String = "",

        var password: String = ""


)

创建UserRepository

  • 增加 @RepositoryRestResource注解 关于 @RepositoryRestResource详细的使用介绍,请参考: https://springcloud.cc/spring-data-rest-zhcn.html
代码语言:javascript
复制
import name.quanke.kotlin.chaper11_6_7.entity.User
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import org.springframework.data.rest.core.annotation.RepositoryRestResource

@RepositoryRestResource(path="user")
interface UserRepository : JpaRepository<User, Long> {

    fun findByUsername(username: String): List<User>

    fun findByUsernameAndPassword(username: String, password: String?): User

    @Query("from User u where u.username=:username")
    fun findUser(@Param("username") username: String): User

}

配置

application.yml文件中增加

代码语言:javascript
复制
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver

启动

代码语言:javascript
复制
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication


/**
 * Created by http://quanke.name on 2018/1/9.
 */

//参考:http://blog.csdn.net/soul_code/article/details/54108105

@SpringBootApplication
class Application

fun main(args: Array<String>) {
    SpringApplication.run(Application::class.java, *args)
}

测试

访问 127.0.0.1:8080/user

返回:

代码语言:javascript
复制
{
    "_embedded": {
        "users": [
            {
                "username": "http://gof.quanke.name",
                "password": "1111",
                "_links": {
                    "self": {
                        "href": "http://127.0.0.1:8083/user/73"
                    },
                    "user": {
                        "href": "http://127.0.0.1:8083/user/73"
                    }
                }
            },
            {
                "username": "java.quanke.name",
                "password": "12",
                "_links": {
                    "self": {
                        "href": "http://127.0.0.1:8083/user/74"
                    },
                    "user": {
                        "href": "http://127.0.0.1:8083/user/74"
                    }
                }
            },
            {
                "username": "test.quanke.name",
                "password": "aa",
                "_links": {
                    "self": {
                        "href": "http://127.0.0.1:8083/user/75"
                    },
                    "user": {
                        "href": "http://127.0.0.1:8083/user/75"
                    }
                }
            },
            {
                "username": "es.quanke.name",
                "password": "12",
                "_links": {
                    "self": {
                        "href": "http://127.0.0.1:8083/user/76"
                    },
                    "user": {
                        "href": "http://127.0.0.1:8083/user/76"
                    }
                }
            },
            {
                "username": "as.quanke.name",
                "password": "12",
                "_links": {
                    "self": {
                        "href": "http://127.0.0.1:8083/user/77"
                    },
                    "user": {
                        "href": "http://127.0.0.1:8083/user/77"
                    }
                }
            },
            {
                "username": "vertx.quanke.name",
                "password": "12",
                "_links": {
                    "self": {
                        "href": "http://127.0.0.1:8083/user/78"
                    },
                    "user": {
                        "href": "http://127.0.0.1:8083/user/78"
                    }
                }
            }
        ]
    },
    "_links": {
        "self": {
            "href": "http://127.0.0.1:8083/user{?page,size,sort}",
            "templated": true
        },
        "profile": {
            "href": "http://127.0.0.1:8083/profile/user"
        },
        "search": {
            "href": "http://127.0.0.1:8083/user/search"
        }
    },
    "page": {
        "size": 20,
        "totalElements": 6,
        "totalPages": 1,
        "number": 0
    }
}

访问 127.0.0.1:8083/user/73

注意: 73 是user id 根据自己的实际情况测试

返回:

代码语言:javascript
复制
{
    "username": "http://gof.quanke.name",
    "password": "1111",
    "_links": {
        "self": {
            "href": "http://127.0.0.1:8083/user/73"
        },
        "user": {
            "href": "http://127.0.0.1:8083/user/73"
        }
    }
}

Spring Data REST 能做的事情很多,这篇文章先介绍到这里,先在这里埋个坑,之后会出更加详细的文章说Spring Data REST。

更多Spring Boot 和 kotlin相关内容

欢迎关注《Spring Boot 与 kotlin 实战》

参考

  • https://springcloud.cc/spring-data-rest-zhcn.html
  • https://www.jianshu.com/p/84f2bbffb885
  • https://www.cnblogs.com/aguncn/p/6762392.html
  • http://blog.csdn.net/soul_code/article/details/54108105
  • https://github.com/spring-projects/spring-data-examples/tree/master/rest
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-01-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 全栈架构 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 将Spring Data REST添加到Spring Boot项目
  • 创建对象User
  • 创建UserRepository
  • 配置
  • 启动
  • 测试
  • 参考
相关产品与服务
云数据库 MongoDB
腾讯云数据库 MongoDB(TencentDB for MongoDB)是腾讯云基于全球广受欢迎的 MongoDB 打造的高性能 NoSQL 数据库,100%完全兼容 MongoDB 协议,支持跨文档事务,提供稳定丰富的监控管理,弹性可扩展、自动容灾,适用于文档型数据库场景,您无需自建灾备体系及控制管理系统。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档