<!-- data jpa and db -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-data-jpa</artifactid>
</dependency>
<dependency>
<groupid>com.h2database</groupid>
<artifactid>h2</artifactid>
<scope>runtime</scope>
</dependency>
创建user实体
package com.edurt.ski.model
import javax.persistence.entity
import javax.persistence.generatedvalue
import javax.persistence.id
@entity
//class usermodel(
// @id
// @generatedvalue
// private var id: long? = 0,
// private var name: string
//)
class usermodel {
@id
@generatedvalue
var id: long? = 0
get() = field
set
var name: string? = null
get() = field
set
}
package com.edurt.ski.service
import com.edurt.ski.model.usermodel
interface userservice {
/**
* save model to db
*/
fun save(model: usermodel): usermodel
}
创建userserviceimpl实现类
package com.edurt.ski.service
import com.edurt.ski.model.usermodel
import com.edurt.ski.support.usersupport
import org.springframework.stereotype.service
@service(value = "userservice")
class userserviceimpl(private val usersupport: usersupport) : userservice {
override fun save(model: usermodel): usermodel {
return this.usersupport.save(model)
}
}
创建用户usercontroller进行持久化数据
package com.edurt.ski.controller
import com.edurt.ski.model.usermodel
import com.edurt.ski.service.userservice
import org.springframework.web.bind.annotation.pathvariable
import org.springframework.web.bind.annotation.postmapping
import org.springframework.web.bind.annotation.requestmapping
import org.springframework.web.bind.annotation.restcontroller
@restcontroller
@requestmapping(value = "user")
class usercontroller(private val userservice: userservice) {
@postmapping(value = "save/{name}")
fun save(@pathvariable name: string): usermodel {
val usermodel = usermodel()
// usermodel.id = 1
usermodel.name = name
return this.userservice.save(usermodel)
}
}
使用控制台窗口执行以下命令保存数据
curl -x post http://localhost:8080/user/save/qianmoq
收到返回结果
{"id":1,"name":"qianmoq"}
表示数据保存成功 增加数据读取渲染功能
修改userservice增加以下代码
/**
* get all model
*/
fun getall(page: pageable): page<usermodel>
修改userserviceimpl增加以下代码
override fun getall(page: pageable): page<usermodel> {
return this.usersupport.findall(page)
}
修改usercontroller增加以下代码
@getmapping(value = "list")
fun get(): page<usermodel> = this.userservice.getall(pagerequest(0, 10))