java后台如何实现让用户可以在页面修改数据表_长见识了,Kotlin + SpringBoot + JPA 整合开发比Java更爽......
點擊上方藍色字體,選擇“標星公眾號”
優質文章,第一時間送達
關注公眾號后臺回復pay或mall獲取實戰項目資料+視頻
作者:ride
segmentfault.com/a/1190000014912005?utm_source=sf-related
開始前需要有java基礎, SpringBoot基礎和kotlin基礎
kotlin參考kotlin中文站的教程, 相信對于一個Java程序員來說, 半天就能上手了
為什么選擇Kotlin
Kotlin比起java來說更加簡潔, 和java一樣是基于JVM的編程語言, 網上關于Kotlin優點缺點的討論也有很多, 這里就不展開了.
之前對于kotlin的了解甚少, 只知道在去年的google I/O大會上成了安卓的第一語言, 其他就不了解了. 現在趁暑假前, 先學習一下kotlin.
教程開始
創建一個SpringBoot工程
首先當然是使用IDEA創建一個SpringBoot工程
這里語言選擇Kotlin, 使用gradle進行管理, 之后再選擇模塊的時候只要選擇上web, jpa和mysql就可以了
然后修改配置文件, 因為導入了jpa, 所以一定要設置好DataSource, 否則無法啟動
spring:??datasource:
????driver-class-name:?com.mysql.jdbc.Driver
????username:?root
????password:?ABCabc123#
????url:?jdbc:mysql://localhost:3306/db_test?useSSL=false
配置完成后可以, 在source目錄下可以看到已經創建好了一個Application.kt文件, 用于啟動SpringBoot, 對應Java下的Application.java 文件
@SpringBootApplicationclass?TestApplication
fun?main(args:?Array)?{
????runApplication(*args)
}
創建Controller
@RestController@RequestMapping("/hello")
class?HelloController?{
????@GetMapping
????fun?hello():String?{
????????return?"hello?world"
????}
}
和java的寫法非常像, 可以無縫轉換
啟動!
使用curl命令進行請求
???~?curl?"http://localhost:8080/hello"hello?world??????????????????????????????????????????????????????????
簡單的請求完成了
使用Swagger2生成接口文檔
使用Swagger2可以自動生成接口文檔和進行接口測試, 極大的方便了后端, 不需要去花很大的功夫獲去維護文檔
首先試試導入Swagger2
????compile?group:?'io.springfox',?name:?'springfox-swagger2',?version:?'2.8.0'????compile?group:?'io.springfox',?name:?'springfox-swagger-ui',?version:?'2.8.0'
配置Swagger2
@Configuration@EnableSwagger2
class?Swagger2?{
????@Bean
????fun?createRestApi():?Docket?{
????????return?Docket(DocumentationType.SWAGGER_2)??//?使用Swagger2
????????????????.apiInfo(apiInfo())?????????????????//?設置接口頁面信息
????????????????.select()???????????????????????????//?返回ApiSelectorBuilder的實例
????????????????.apis(RequestHandlerSelectors.basePackage("io.ride.vote.web"))??????//?api接口所在的包
????????????????.paths(PathSelectors.any())?????????
????????????????.build()
????}
????/**
?????*?頁面信息展示
?????*/
????private?fun?apiInfo():?ApiInfo?{
????????return?ApiInfoBuilder()
????????????????.title("Vote?RestFul?APIs文檔")
????????????????.description("項目API接口文檔")
????????????????.contact(Contact("ride",?"",?"supreDong@gamil.com"))
????????????????.version("0.0.1")
????????????????.build()
????}
}
***@Configuration***注解表明這是一個配置類, ***@EnableSwagger2***注解表明啟用Swagger2
通過在controller中添加注解來生成api文檔
@Api(value?=?"測試",?description?=?"測試控制器")@RestController
@RequestMapping("/hello")
class?HelloController?{
????@GetMapping
????@ApiOperation("你好!世界!",?notes?=?"返回hello?world")
????fun?hello():?String?{
????????return?"hello?world"
????}
}
之后打開**http://localhost:8080/swagger-ui.html**可以看到生成的接口信息如圖, 在該頁面上還以對接口進行測試
統一異常處理
和java下的操作是一致的, 只是把java翻譯成了kotlin
@ControllerAdviceclass?CustomExceptionHandler?{
????@ExceptionHandler(ApiException::class)
????fun?handlerApiException(e:?ApiException):?ResponseEntity?{
????????val?result?=?Result(e.code,?e.data)return?result.ok()
????}
????@ExceptionHandler(MissingServletRequestParameterException::class)
????fun?handMissingServletRequestParameterException(e:?MissingServletRequestParameterException):?ResponseEntity?{
????????val?result?=?Result(HttpStatus.BAD_REQUEST.value(),?e.message)return?result.ok()
????}
}
class?ApiException(val?code:?ResultCode,?val?data:?HashMap??=?null)?:?RuntimeException(code.msg)
使用JPA
首先配置JPA:
spring:??jpa:
????show-sql:?true
????hibernate:
??????ddl-auto:?update
????database:?mysql
創建data類
@Entity@Table(name?=?"t_user")
data?class?User(
????????@Id
????????@GeneratedValue(strategy?=?GenerationType.IDENTITY)
????????var?id:?Long?=?-1,
????????@Column(nullable?=?false)
????????var?username:?String??=?null,
????????@Column(nullable?=?false)
????????var?password:?String??=?null,
????????@Column(nullable?=?false)
????????var?email:?String??=?null,
????????@Column(nullable?=?true)
????????var?nickname:?String??=?null,
????????@Column(nullable?=?false)
????????var?createTime:?Date?=?Date()
)
創建repository類
interface?IUserService?{????/**
?????*?添加一個用戶
?????*/
????fun?addUser(user:?User):?User
????/**
?????*?展示所有用戶
?????*/
????fun?listAll():?List
????/**
?????*?刪除一個用戶
?????*/
????fun?deleteUser(id:?Long)
}
進行單元測試
@RunWith(SpringRunner::class)@SpringBootTest
class?UserRepositoryTest?{
????@Autowired
????private?lateinit?var?userRepository:?UserRepository
????@Test
????fun?`find?all?user?test`()?{
????????println(userRepository.findAll())
????}
????@Test
????fun?`add?user?test`()?{
????????val?user?=?User(username?=?"ride",?email?=?"supreDong@gmail.com",?password?=?"123123",?nickname?=?"ride")
????????println(userRepository.save(user))
????}
????@Test
????fun?`delete?user?test`()?{
????????val?user?=?userRepository.findById(1)
????????println(user.orElse(null))
????????if?(user.isPresent)
????????????userRepository.deleteById(user.get().id)
????}
}
在單元測試并且只能在單元測試中(kotlin1.2)可以使用反引號來定義方法
總結
使用使用kotlin結合SpringBoot是一種從船新體驗, 推薦大家嘗試一下
有熱門推薦?
Java實現QQ登錄和微博登錄
推薦 5 款好用的REST API工具
一口氣說了 6種 數據脫敏方案,大廠也這么用!
新技能 MyBatis 千萬數據表,快速分頁!
2020搞個 Mac 玩玩
10w行級別數據的Excel導入,4版完整優化記錄,效果太明顯了!
用Java實現一個抽獎系統(附完整代碼)
推薦一個基于SpringBoot + Mybatis + Vue的代碼生成器
點擊SpringCloud實戰項目
總結
以上是生活随笔為你收集整理的java后台如何实现让用户可以在页面修改数据表_长见识了,Kotlin + SpringBoot + JPA 整合开发比Java更爽......的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++与C中const的比较以及cons
- 下一篇: JAVA版游戏下载_我的世界Java版2