Spring Boot与Kotlin的优势
传统的Spring框架配置繁琐,对于并发压力不大的业务场景,若只需快速启动RESTful服务,过度纠结于XML配置显得多余。为解决这一痛点,Spring Boot应运而生。同时,为了规避Java 8开发中的冗长问题,Kotlin成为更优选择。
本方案选用MySQL作为数据源,借助Spring Boot极简配置特性,结合Spring Data JPA与Hibernate实现对数据的访问与管理。
Gradle依赖处理
处理依赖
项目依赖管理采用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构建文件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'
}
JPA配置文件设置
配置文件
在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实体类定义
创建一个简单的实体类
此处定义一个简单的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 2026/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特性,其最大优势在于自动省略getter、setter以及toString()方法的定义,这些功能均已默认实现。因此,在使用data class对象时,可直接通过name、email以及id等属性进行访问。
无参构造函数专为JPA设计,故访问级别设为protected;主构造函数则用于创建与数据库操作相关的对象实例。
整个类由@Entity注解修饰,标识其为JPA实体类。@Table注解指定了该类对应的数据库表名。
被@Id注解修饰的User类的id属性被视为对象的ID。同时,@GeneratedValue(strategy = GenerationType.AUTO)注解表明该ID采用自动生成策略。
其余两个属性name和email受@Column(nullable = false)注解约束,表示这两列均不可为空,且列名与属性名一致。若需不同名,可采用@Column(nullable = false, name="XXXXXX")。形式指定。
Repository接口实现
创建简单的查询接口(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 {
fun findByEmail(email: String): User?
}
泛型类型参数分别为User及其ID类型:User和Long。除了基础的CRUD操作,还可自定义查询方法。例如在上述代码中定义了findByEmail()方法。关于自定义查询的具体命名规则,请参阅相关文档。
Controller测试验证
用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 2026/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信息。
以上内容涵盖了基于Kotlin和Spring Boot构建RESTful服务的核心步骤,希望对读者有所帮助,欢迎继续支持本站获取更多技术分享。