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/

用Kotlin写一个基于Spring Boot的RESTful服务的更多相关文章

  1. 手把手写一个基于Spring Boot框架下的参数校验组件(JSR-303)

    前言 之前参与的新开放平台研发的过程中,由于不同的接口需要对不同的入参进行校验,这就涉及到通用参数的校验封装,如果不进行封装,那么写出来的校验代码将会风格不统一.校验工具类不一致.维护风险高等其它因素 ...

  2. Spring Boot入门第二天:一个基于Spring Boot的Web应用,使用了Spring Data JPA和Freemarker。

    原文链接 今天打算从数据库中取数据,并展示到视图中.不多说,先上图: 第一步:添加依赖.打开pom.xml文件,添加必要的依赖,完整代码如下: <?xml version="1.0&q ...

  3. SpringBootService,一个基于spring boot搭建的SOA服务框架

    SpringBootService,这是一个spring boot微服务的框架,包括redis,mq,restful,定时器,mybatis.易扩容.易维护的架构. 项目说明 该项目使用maven进行 ...

  4. 基于Spring Boot的微服务搭建

    环境: 项目结构: 关键配置 pom.xml <?xml version="1.0" encoding="UTF-8"?> <project ...

  5. 基于Spring Boot的RESTful API实践(一)

    1. RESTful简述    REST是一种设计风格,是一组约束条件及原则,而遵循REST风格的架构就称为RESTful架构,资源是RESTful的核心,一个好的RESTful架构,通过URL就能很 ...

  6. spring boot构建restful服务

    使用spring boot快速构建出restful服务 JPA实现REST 创建spring boot项目,在项目文件pom.xml中添加以下依赖: <dependency> <gr ...

  7. 基于Spring Boot的问答系统之一:elasticsearch 7.2的hello world入门

    好久没有写代码了,最近想做一个基于spring boot + vue + elasticsearch + NLP(语义相关性)的小系统练练手,系统后面可以成为一个聊天机器人,客服系统的原型等等. 所以 ...

  8. 基于Spring Boot的图片上传

    package com.clou.inteface.domain.web.user; import java.io.File; import java.io.IOException; import j ...

  9. Spring Boot 是 Spring 的一套快速配置脚手架,可以基于Spring Boot 快速开发单个微服务

    Spring Boot 是 Spring 的一套快速配置脚手架,可以基于Spring Boot 快速开发单个微服务,Spring Cloud是一个基于Spring Boot实现的云应用开发工具:Spr ...

随机推荐

  1. mysql 复制原理与实践

    复制功能是将一个mysql数据库上的数据复到一个或多个mysql从数据库上. 复制的原理:在主服务器上执行的所有DDL和DML语句都会被记录到二进制日志中,这些日志由连接到它的从服务器获取,并复制到从 ...

  2. YII2中使用控制台命令

    有些时候我们需要通过crontab在后台跑一些定时脚本,这时候就需要用到控制台命令了. 我们在commands目录下创建TestController.php,当然脚本的位置是可以随意指定的,只需要在c ...

  3. android 开发概述以及相关背景知识

    参考链接:http://www.runoob.com/android/android-architecture.html http://www.runoob.com/android/android-a ...

  4. c# 运行大运算程序主窗体卡掉的解决

    写了一个运算过滤大文本的程序, 其中方法里边使用了多线程,并行线程等方法.  但主窗体控件直接使用此方法时,页面卡顿.所以主线程被堵塞. 代码如下, splitfile 这个方法运行时页面卡顿,阻塞了 ...

  5. 23.Mysql应用优化

    23.应用优化23.1 使用连接池应用启动时创建好连接,以供用户使用,而不是每次创建. 23.2 减少对Mysql的访问 23.2.1 避免对同一数据做重复检索合并简单查询,减少访问次数. 23.2. ...

  6. Oracle_SQL(6) 单行函数

    一.单行函数1.定义:对表或视图的查询时,针对每行记录返回一个值的函数.2.用途:用于select语句,where条件3.分类: 数值函数 Number Functions 字符函数(返回字符) Ch ...

  7. OpenSource.SerializationLibrary

    1. Cap'n Proto protocol buffer的主要作者之一创建的新项目.其主页描述Cap'n Proto的性能比PB快很多. http://kentonv.github.io/capn ...

  8. Linux服务器有什么优势?

    为您的企业选择服务器时,您可以选择几种不同的选项.虽然许多公司使用基于Windows的服务器,但选择Linux服务器可能是您最好的选择.为什么Linux服务器比其他服务器更好?以下是使用Linux服务 ...

  9. java中 this 关键字的三种用法

    Java中this的三种用法 调用属性 (1)this可以调用本类中的任何成员变量 调用方法(可省略) (2)this调用本类中的成员方法(在main方法里面没有办法通过this调用) 调用构造方法 ...

  10. sed删除行

    删除文件中含有$word字符串的某些行(在文件中修改) sed -i '/$word/d' file