Kotlin中文文档

Kotlin中文文档

Kotlin中文文档
在线调试

在线调试

Kotlin在线调试工具
开发工具

开发工具

Kotlin开发工具IntelliJ IDEA
技术问答

技术问答

Kotlin技术问答与交流专区

Kotlin+SpringBoot服务端restful框架搭建(3)简单集成swagger2

Cat 发表了文章 • 3 个评论 • 360 次浏览 • 2018-04-04 15:46 • 来自相关话题

添加依赖

在之前的的项目添加这些swagger2依赖的类
 
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>注意:本文只是简单的做集成,目前尝试可以正常启动显示接口信息,但是对于部分嵌套的注解添加会报错,目前还没找到解决方案。 @APiresponses()和@ApiImplicitParams()使用时回报错。
 
添加swagger2配置类

这个配置springboot中使用swagger2类似
package com.kotliner.demo
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import springfox.documentation.builders.ApiInfoBuilder
import springfox.documentation.builders.PathSelectors
import springfox.documentation.builders.RequestHandlerSelectors
import springfox.documentation.service.ApiInfo
import springfox.documentation.spi.DocumentationType
import springfox.documentation.spring.web.plugins.Docket
import springfox.documentation.swagger2.annotations.EnableSwagger2

@Configuration
@EnableSwagger2
class Swagger{


@Bean
fun createRestApi():Docket{
var docket = Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("业务系统API接口文档")
.select()
.apis(RequestHandlerSelectors.basePackage("com.kotliner.demo"))
.paths(PathSelectors.any())
.build();
return docket;
}

fun apiInfo():ApiInfo{

var api = ApiInfoBuilder()
.title("业务系统名称")
.description("swagger2构建框架restfull API文档")
.contact("猫")
.version("1.0")
.termsOfServiceUrl("")
.build();
return api;

}


}
conroller添加swagger2注解
 
目前只使用了@Api,@ApiOperation,@ApiPara,添加完成后我们就可以启动了。
 
package com.kotliner.demo.controller

import com.kotliner.demo.entity.CaOrder
import com.kotliner.demo.mapper.OrderMapper
import com.kotliner.demo.service.ICaOrderService
import io.swagger.annotations.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*

@Api(value = "order",description = "订单业务")
@RestController
class OrderController{

@Autowired
lateinit var service: ICaOrderService;
@Autowired
lateinit var mapper: OrderMapper


@ApiOperation(value = "订单查询",notes = "订单列表查询")
@RequestMapping(value = "/findAllOrder",method = arrayOf(RequestMethod.POST))
fun findAllOrder(@ApiParam(name="order",value = "订单",required = true) @RequestBody order: CaOrder):List<CaOrder>{
return service.findAllOrder(order);
}

@ApiOperation(value = "订单查询",notes = "订单列表查询")
@RequestMapping(value = "/find",method = arrayOf(RequestMethod.POST))
fun find(@ApiParam(name="order",value = "订单",required = true) @RequestBody order: CaOrder):String{
var orders: List<CaOrder> = mapper.findOrderList(order);


return "ssssssssssss"+orders.toString();
}

@ApiOperation(value = "新增订单",notes = "新增订单")
@RequestMapping(value = "/save",method = arrayOf(RequestMethod.POST))
fun save(@ApiParam(name="order",value = "订单",required = true) @RequestBody order: CaOrder):Int{
return service.saveOrder(order);
}

@ApiOperation(value = "修改订单",notes = "修改订单")
@RequestMapping(value = "/update",method = arrayOf(RequestMethod.POST))
fun update(@ApiParam(name="order",value = "订单",required = true) @RequestBody order: CaOrder):Int{
return service.updateOrder(order);
}


@ApiOperation(value = "根据id删除订单",notes = "根据id删除订单")
@RequestMapping(value = "/delete",method = arrayOf(RequestMethod.GET))
fun delete(@ApiParam(name="id",value = "订单id",required = true) @RequestParam(value = "id") id:Int){
service.deleteOrder(id);
}
}访问

输入http://localhost:8090/demo/swagger-ui.html地址就可以看到了,新版本的swagger界面做了改版。 查看全部
添加依赖

在之前的的项目添加这些swagger2依赖的类
 
   <dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
注意:本文只是简单的做集成,目前尝试可以正常启动显示接口信息,但是对于部分嵌套的注解添加会报错,目前还没找到解决方案。 @APiresponses()和@ApiImplicitParams()使用时回报错。
 
添加swagger2配置类

这个配置springboot中使用swagger2类似
package com.kotliner.demo
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import springfox.documentation.builders.ApiInfoBuilder
import springfox.documentation.builders.PathSelectors
import springfox.documentation.builders.RequestHandlerSelectors
import springfox.documentation.service.ApiInfo
import springfox.documentation.spi.DocumentationType
import springfox.documentation.spring.web.plugins.Docket
import springfox.documentation.swagger2.annotations.EnableSwagger2

@Configuration
@EnableSwagger2
class Swagger{


@Bean
fun createRestApi():Docket{
var docket = Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("业务系统API接口文档")
.select()
.apis(RequestHandlerSelectors.basePackage("com.kotliner.demo"))
.paths(PathSelectors.any())
.build();
return docket;
}

fun apiInfo():ApiInfo{

var api = ApiInfoBuilder()
.title("业务系统名称")
.description("swagger2构建框架restfull API文档")
.contact("猫")
.version("1.0")
.termsOfServiceUrl("")
.build();
return api;

}


}

conroller添加swagger2注解
 
目前只使用了@Api,@ApiOperation,@ApiPara,添加完成后我们就可以启动了。
 
package com.kotliner.demo.controller

import com.kotliner.demo.entity.CaOrder
import com.kotliner.demo.mapper.OrderMapper
import com.kotliner.demo.service.ICaOrderService
import io.swagger.annotations.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*

@Api(value = "order",description = "订单业务")
@RestController
class OrderController{

@Autowired
lateinit var service: ICaOrderService;
@Autowired
lateinit var mapper: OrderMapper


@ApiOperation(value = "订单查询",notes = "订单列表查询")
@RequestMapping(value = "/findAllOrder",method = arrayOf(RequestMethod.POST))
fun findAllOrder(@ApiParam(name="order",value = "订单",required = true) @RequestBody order: CaOrder):List<CaOrder>{
return service.findAllOrder(order);
}

@ApiOperation(value = "订单查询",notes = "订单列表查询")
@RequestMapping(value = "/find",method = arrayOf(RequestMethod.POST))
fun find(@ApiParam(name="order",value = "订单",required = true) @RequestBody order: CaOrder):String{
var orders: List<CaOrder> = mapper.findOrderList(order);


return "ssssssssssss"+orders.toString();
}

@ApiOperation(value = "新增订单",notes = "新增订单")
@RequestMapping(value = "/save",method = arrayOf(RequestMethod.POST))
fun save(@ApiParam(name="order",value = "订单",required = true) @RequestBody order: CaOrder):Int{
return service.saveOrder(order);
}

@ApiOperation(value = "修改订单",notes = "修改订单")
@RequestMapping(value = "/update",method = arrayOf(RequestMethod.POST))
fun update(@ApiParam(name="order",value = "订单",required = true) @RequestBody order: CaOrder):Int{
return service.updateOrder(order);
}


@ApiOperation(value = "根据id删除订单",notes = "根据id删除订单")
@RequestMapping(value = "/delete",method = arrayOf(RequestMethod.GET))
fun delete(@ApiParam(name="id",value = "订单id",required = true) @RequestParam(value = "id") id:Int){
service.deleteOrder(id);
}
}
访问

输入http://localhost:8090/demo/swagger-ui.html地址就可以看到了,新版本的swagger界面做了改版。

Kotlin+SpringBoot服务端restful框架搭建(2)集成mybatis

Cat 发表了文章 • 0 个评论 • 412 次浏览 • 2018-04-03 16:51 • 来自相关话题

搭建完成简单的kotlin集成SpringBoot的框架,我们再来尝试把mybatis也集成进去,数据库我们采用mysql。
 
要求
mybatismysql

快速搭建

1.创建一张表,表名ca_order
ID int订单编号 order_no varchar(10)订单金额 order_amount double订单创建时间 create_time datetime订单创建人 create_user varchar(10)支付方式 pay_type varchar(10)商品名称 commodity_name varchar(30)商品数量 commodity_num int
 
DROP TABLE IF EXISTS `ca_order`;
CREATE TABLE `ca_order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_no` varchar(20) DEFAULT NULL,
`order_amount` double(10,2) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`create_user` varchar(20) DEFAULT NULL,
`pay_type` varchar(10) DEFAULT NULL,
`commodity_name` varchar(20) DEFAULT NULL,
`commodity_num` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1001', 1000, NOW(), '张三', '支付宝', '手机', 1);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1002', 2799.00, NOW(), '张小凡', '支付宝','荣耀v10',1);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1003', 16863.00, NOW(), '郭靖', '银联', 'iPhoneX', 2);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1004', 2677.00, NOW(), '张三风', '支付宝', 'vivoX21',1);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1005', 4325.78, NOW(), '谢逊', '微信', '诺基亚', 3);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1006', 2001, NOW(), '杨过', '支付宝', '小米mix', 2);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1007', 4399.00, NOW(), '张无忌', '微信', '华为P20',1);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1008', 2999, NOW(), '陈震', '支付宝', '荣耀v9', 3);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1009', 1999, NOW(), '李狗蛋', '信用卡', '小米6',1);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1010', 3200, NOW(), '郭德纲', '支付宝', 'iPhone6s', 1);

2.在application.yml添加datasource
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/csdata?useUnicode=true&characterEncoding=utf-8
username: root
password: 123456
driverClassName: com.mysql.jdbc.Driver引入我们需要的mybatis和mysql
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>3.创建实体类。kotlin创建实体类方式有两种,一种是类似java的class,一种是kotlin的data class(数据类)。数据类(data class)必须满足以下要求:
主构造函数至少有一个参数;主构造函数的所有参数需标记为val 或 var;数据类不能是抽象、开放、密封或者内部的;自kotlin 1.1起,数据类可以扩展其他类;在1.1之前,数据类只能实现接口

编译器会为数据类(data class)自动生成以下函数:
equals()/hashCode()toString()componentN()copy()

lateinit只能用于非基本数据类型。Kotlin会使用null来对每一个用lateinit修饰的属性做初始化,而基础类型是没有null类型。
 
class
class CaOrder {
var id:Int=0
var orderNo:String=""
var orderAmount:Double=0.00
var createTime:String=""
var createUser:String=""
var payType:String=""
var commodityName:String=""
var commodityNum:Int=0
}开始使用lateinit var定义属性,但是运行的时候提示lateinit property has not been initialized,目前没找到解决方法,就直接给属性设置个默认值了
 
data class
 
data class CaOrder(
var id:Int?,
var orderNo:String,
var orderAmount:Double?,
var createTime:String,
var createUser:String,
var payType:String,
var commodityName:String,
var commodityNum:Int?
)注意:Int后面的?号,如果不加这个问号,运行的时候会报No constructor found in void matching的错误。原因是Int是kotlin的基础数据类型不能为null,会被映射成java中int,而实体类对应数据的时候某些字段会出现空值的,这就使kotlin在转成实体类的时候不确定转成int还是Integer,而加上问号之后是告诉它这个属性为空值的时候就返回null。具体可以参考一下kotlin的?的使用方法。
 
4.创建Mapper,两种方式来实现Mapper,一种是通过注解标签@select,@insert,@update,@delete,另一种通过xml配置文件,还是推荐使用xml吧,使用起来相对方便,动态sql写起来更容易。
 
第一种。

实体类CaOrderDao
 
package com.kotliner.demo.mapper

import com.kotliner.demo.entity.CaOrder
import org.apache.ibatis.annotations.*

@Mapper
interface CaOrderMapper{

@Select("""
select id,order_no as orderNo, order_amount, date_format(create_time,'%Y-%m-%d %H:%i:%s') as create_time, create_user, pay_type, commodity_name, commodity_num from ca_order
""")
fun findOrderList(order: CaOrder):List<CaOrder>;


@Insert("""
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES
(#{orderNo},#{orderAmount},NOW(),#{createUser},#{payType},#{commodityName},#{commodityNum})
""")
fun saveOrder(order: CaOrder):Int;


@Update("""
update ca_order set order_amount=#{orderAmount} where id=#{id}
""")
fun updateOrder(order: CaOrder):Int;

@Delete("""
delete from ca_order where id=#{id}
""")
fun deleteOrder(id:Int)
}第二种,如果使用这种需要再application.yml添加如下代码用来指定xml位置
 
mybatis:
type-aliases-package: com.kotliner.demo.entity
mapper-locations: classpath:mapper/*.xml这时候mapperr类就变得简单了
 
package com.kotliner.demo.mapper

import com.kotliner.demo.entity.CaOrder
import org.apache.ibatis.annotations.Mapper

@Mapper
interface CaOrderMapper{

fun findOrderList(order: CaOrder):List<CaOrder>;
fun saveOrder(order: CaOrder):Int;
fun updateOrder(order: CaOrder):Int;
fun deleteOrder(id:Int);
}然后在resource下面创建Mapper文件,放入xml文件
<mapper namespace="com.kotliner.demo.mapper.OrderMapper">

<!-- 实体类映射-->
<resultMap type="com.kotliner.demo.entity.CaOrder" id="OrderMap">
<result column="id" property="id"/>
<result column="order_no" property="orderNo"/>
<result column="order_amount" property="orderAmount"/>
<result column="create_time" property="createTime"/>
<result column="create_user" property="createUser"/>
<result column="pay_type" property="payType"/>
<result column="commodity_name" property="commodityName"/>
<result column="commodity_num" property="commodityNum"/>
</resultMap>
<!-- 按条件查询-->

<select id="findOrderList" parameterType="com.kotliner.demo.entity.CaOrder" resultMap="OrderMap" >
select id,order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num from ca_order
</select>


</mapper>5.创建service和controller
 
服务接口ICaOrderService
package com.kotliner.demo.service

import com.kotliner.demo.entity.CaOrder


interface ICaOrderService{

fun findAllOrder(order: CaOrder):List<CaOrder>;

fun saveOrder(order: CaOrder):Int;

fun updateOrder(order: CaOrder):Int;

fun deleteOrder(id: Int);
}服务实现类CaOrderMapper
 
package com.kotliner.demo.service


import com.kotliner.demo.entity.CaOrder
import com.kotliner.demo.mapper.CaOrderMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service


@Service
class CaOrderImpl : ICaOrderService {

@Autowired
lateinit var dao: CaOrderMapper;

override fun findAllOrder(order: CaOrder): List<CaOrder> {
return dao.findOrderList(order);

}

override fun saveOrder(order: CaOrder): Int {
return dao.saveOrder(order);
}

override fun updateOrder(order: CaOrder): Int {
return dao.updateOrder(order);
}

override fun deleteOrder(id: Int) {
dao.deleteOrder(id);
}

}注解的使用同java相同,只是具体方法属性定义需要注意
 
OrderController类
 
package com.kotliner.demo.controller

import com.kotliner.demo.entity.CaOrder
import com.kotliner.demo.mapper.OrderMapper
import com.kotliner.demo.service.ICaOrderService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*


@RestController
class OrderController{

@Autowired
lateinit var service: ICaOrderService


@RequestMapping(value = "/findAllOrder",method = arrayOf(RequestMethod.POST))
fun findAllOrder(@RequestBody order: CaOrder):List<CaOrder>{
return service.findAllOrder(order);
}

@RequestMapping(value = "/save",method = arrayOf(RequestMethod.POST))
fun save(@RequestBody order: CaOrder):Int{
return service.saveOrder(order);
}

@RequestMapping(value = "/update",method = arrayOf(RequestMethod.POST))
fun update(@RequestBody order: CaOrder):Int{
return service.updateOrder(order);
}
@RequestMapping(value = "/delete",method = arrayOf(RequestMethod.GET))
fun delete(@RequestParam(value = "id") id:Int){
service.deleteOrder(id);
}
}
创建完成,启动一下服务。

创建的接口基本都是post的方式,我们通过postman来调试接口。 查看全部
搭建完成简单的kotlin集成SpringBoot的框架,我们再来尝试把mybatis也集成进去,数据库我们采用mysql。
 
要求
  • mybatis
  • mysql


快速搭建

1.创建一张表,表名ca_order
  • ID int
  • 订单编号 order_no varchar(10)
  • 订单金额 order_amount double
  • 订单创建时间 create_time datetime
  • 订单创建人 create_user varchar(10)
  • 支付方式 pay_type varchar(10)
  • 商品名称 commodity_name varchar(30)
  • 商品数量 commodity_num int

 
DROP TABLE IF EXISTS `ca_order`;
CREATE TABLE `ca_order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_no` varchar(20) DEFAULT NULL,
`order_amount` double(10,2) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`create_user` varchar(20) DEFAULT NULL,
`pay_type` varchar(10) DEFAULT NULL,
`commodity_name` varchar(20) DEFAULT NULL,
`commodity_num` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1001', 1000, NOW(), '张三', '支付宝', '手机', 1);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1002', 2799.00, NOW(), '张小凡', '支付宝','荣耀v10',1);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1003', 16863.00, NOW(), '郭靖', '银联', 'iPhoneX', 2);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1004', 2677.00, NOW(), '张三风', '支付宝', 'vivoX21',1);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1005', 4325.78, NOW(), '谢逊', '微信', '诺基亚', 3);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1006', 2001, NOW(), '杨过', '支付宝', '小米mix', 2);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1007', 4399.00, NOW(), '张无忌', '微信', '华为P20',1);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1008', 2999, NOW(), '陈震', '支付宝', '荣耀v9', 3);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1009', 1999, NOW(), '李狗蛋', '信用卡', '小米6',1);
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES ('1010', 3200, NOW(), '郭德纲', '支付宝', 'iPhone6s', 1);

2.在application.yml添加datasource
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/csdata?useUnicode=true&characterEncoding=utf-8
username: root
password: 123456
driverClassName: com.mysql.jdbc.Driver
引入我们需要的mybatis和mysql
 <dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
3.创建实体类。kotlin创建实体类方式有两种,一种是类似java的class,一种是kotlin的data class(数据类)。数据类(data class)必须满足以下要求:
  • 主构造函数至少有一个参数;
  • 主构造函数的所有参数需标记为val 或 var;
  • 数据类不能是抽象、开放、密封或者内部的;
  • 自kotlin 1.1起,数据类可以扩展其他类;在1.1之前,数据类只能实现接口


编译器会为数据类(data class)自动生成以下函数:
  • equals()/hashCode()
  • toString()
  • componentN()
  • copy()


lateinit只能用于非基本数据类型。Kotlin会使用null来对每一个用lateinit修饰的属性做初始化,而基础类型是没有null类型。
 
class
class CaOrder {
var id:Int=0
var orderNo:String=""
var orderAmount:Double=0.00
var createTime:String=""
var createUser:String=""
var payType:String=""
var commodityName:String=""
var commodityNum:Int=0
}
开始使用lateinit var定义属性,但是运行的时候提示lateinit property has not been initialized,目前没找到解决方法,就直接给属性设置个默认值了
 
data class
 
data class CaOrder(
var id:Int?,
var orderNo:String,
var orderAmount:Double?,
var createTime:String,
var createUser:String,
var payType:String,
var commodityName:String,
var commodityNum:Int?
)
注意:Int后面的?号,如果不加这个问号,运行的时候会报No constructor found in void matching的错误。原因是Int是kotlin的基础数据类型不能为null,会被映射成java中int,而实体类对应数据的时候某些字段会出现空值的,这就使kotlin在转成实体类的时候不确定转成int还是Integer,而加上问号之后是告诉它这个属性为空值的时候就返回null。具体可以参考一下kotlin的?的使用方法。
 
4.创建Mapper,两种方式来实现Mapper,一种是通过注解标签@select,@insert,@update,@delete,另一种通过xml配置文件,还是推荐使用xml吧,使用起来相对方便,动态sql写起来更容易。
 
第一种。

实体类CaOrderDao
 
package com.kotliner.demo.mapper

import com.kotliner.demo.entity.CaOrder
import org.apache.ibatis.annotations.*

@Mapper
interface CaOrderMapper{

@Select("""
select id,order_no as orderNo, order_amount, date_format(create_time,'%Y-%m-%d %H:%i:%s') as create_time, create_user, pay_type, commodity_name, commodity_num from ca_order
""")
fun findOrderList(order: CaOrder):List<CaOrder>;


@Insert("""
INSERT INTO ca_order (order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num) VALUES
(#{orderNo},#{orderAmount},NOW(),#{createUser},#{payType},#{commodityName},#{commodityNum})
""")
fun saveOrder(order: CaOrder):Int;


@Update("""
update ca_order set order_amount=#{orderAmount} where id=#{id}
""")
fun updateOrder(order: CaOrder):Int;

@Delete("""
delete from ca_order where id=#{id}
""")
fun deleteOrder(id:Int)
}
第二种,如果使用这种需要再application.yml添加如下代码用来指定xml位置
 
mybatis:
type-aliases-package: com.kotliner.demo.entity
mapper-locations: classpath:mapper/*.xml
这时候mapperr类就变得简单了
 
package com.kotliner.demo.mapper

import com.kotliner.demo.entity.CaOrder
import org.apache.ibatis.annotations.Mapper

@Mapper
interface CaOrderMapper{

fun findOrderList(order: CaOrder):List<CaOrder>;
fun saveOrder(order: CaOrder):Int;
fun updateOrder(order: CaOrder):Int;
fun deleteOrder(id:Int);
}
然后在resource下面创建Mapper文件,放入xml文件
<mapper namespace="com.kotliner.demo.mapper.OrderMapper">

<!-- 实体类映射-->
<resultMap type="com.kotliner.demo.entity.CaOrder" id="OrderMap">
<result column="id" property="id"/>
<result column="order_no" property="orderNo"/>
<result column="order_amount" property="orderAmount"/>
<result column="create_time" property="createTime"/>
<result column="create_user" property="createUser"/>
<result column="pay_type" property="payType"/>
<result column="commodity_name" property="commodityName"/>
<result column="commodity_num" property="commodityNum"/>
</resultMap>
<!-- 按条件查询-->

<select id="findOrderList" parameterType="com.kotliner.demo.entity.CaOrder" resultMap="OrderMap" >
select id,order_no, order_amount, create_time, create_user, pay_type, commodity_name, commodity_num from ca_order
</select>


</mapper>
5.创建service和controller
 
服务接口ICaOrderService
package com.kotliner.demo.service

import com.kotliner.demo.entity.CaOrder


interface ICaOrderService{

fun findAllOrder(order: CaOrder):List<CaOrder>;

fun saveOrder(order: CaOrder):Int;

fun updateOrder(order: CaOrder):Int;

fun deleteOrder(id: Int);
}
服务实现类CaOrderMapper
 
package com.kotliner.demo.service


import com.kotliner.demo.entity.CaOrder
import com.kotliner.demo.mapper.CaOrderMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service


@Service
class CaOrderImpl : ICaOrderService {

@Autowired
lateinit var dao: CaOrderMapper;

override fun findAllOrder(order: CaOrder): List<CaOrder> {
return dao.findOrderList(order);

}

override fun saveOrder(order: CaOrder): Int {
return dao.saveOrder(order);
}

override fun updateOrder(order: CaOrder): Int {
return dao.updateOrder(order);
}

override fun deleteOrder(id: Int) {
dao.deleteOrder(id);
}

}
注解的使用同java相同,只是具体方法属性定义需要注意
 
OrderController类
 
package com.kotliner.demo.controller

import com.kotliner.demo.entity.CaOrder
import com.kotliner.demo.mapper.OrderMapper
import com.kotliner.demo.service.ICaOrderService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*


@RestController
class OrderController{

@Autowired
lateinit var service: ICaOrderService


@RequestMapping(value = "/findAllOrder",method = arrayOf(RequestMethod.POST))
fun findAllOrder(@RequestBody order: CaOrder):List<CaOrder>{
return service.findAllOrder(order);
}

@RequestMapping(value = "/save",method = arrayOf(RequestMethod.POST))
fun save(@RequestBody order: CaOrder):Int{
return service.saveOrder(order);
}

@RequestMapping(value = "/update",method = arrayOf(RequestMethod.POST))
fun update(@RequestBody order: CaOrder):Int{
return service.updateOrder(order);
}
@RequestMapping(value = "/delete",method = arrayOf(RequestMethod.GET))
fun delete(@RequestParam(value = "id") id:Int){
service.deleteOrder(id);
}
}
创建完成,启动一下服务。

创建的接口基本都是post的方式,我们通过postman来调试接口。

Kotlin+SpringBoot服务端restful框架搭建(1)

Cat 发表了文章 • 0 个评论 • 380 次浏览 • 2018-04-01 15:52 • 来自相关话题

       本文的组要目的是完成SpringBoot集成Kotlin的一个基本项目构建,通过这个例子能够对kotlin有一个简单的了解。与其看着枯燥的教程,看看它的使用也许会更有意思。

kotlin简介
      Kotlin是一个基于JVM的编程语言,由JetBrains设计开发并开源。Kotlin可以编译成Java字节码也可以编译成JavaScript,支持开发Android,并且谷歌已经明确将Kotlin作为Android的一级开发语言。最新的Spring5版本也专门引入了对于Kotlin的支持。Kotlin拥有更简洁的代码,完全兼容java,而且同java可以实现完全的互调。使用Kotlin你起码可以少些30%的代码。
 
要求
JDK 1.8maven构建Spring4IDEA IntellijKotlin 1.2.31
 
快速构建
 
首先构建一个maven项目,我们命名为KotlinDemo。(使用idea构建Kotlin项目需要按照Kotlin的插件。)
1.先来修改pom.xml添加需要使用的依赖。 引入spring-boot-starter-parent,这里使用1.5.6版本
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>添加需要的依赖
<properties>
<java.version>1.8</java.version>
<mybatis.spring.version>1.2.4</mybatis.spring.version>
<kotlin.compiler.incremental>true</kotlin.compiler.incremental>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<kotlin.version>1.2.31</kotlin.version>
</properties><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jre8</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>${kotlin.version}</version>
</dependency>
在build中添加插件
 
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>1.2.31</version>
<configuration>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
<jvmTarget>1.8</jvmTarget>
</configuration>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>1.2.31</version>
</dependency>
</dependencies>
</plugin>
2.创建application.yml
server:
context-path: /kotlin
port: 80903.创建Application.kt文件
 
       创建类的方法同java相似,也是引入各种包,但是需要注意Kotlin的main方法是class外面和java的main方法区别

        添加spring的注解@RestController和@SpringBootApplication,我们在class里面创建一个简单的restfull格式的请求方法hello(),方法返一个String的字符串。

       添加@RequestMapping时候需要注意设置method的时候,这里method接收的是一个数组,不是RequestMethod.GE,所以我们需要通过kotlin提供的arrayOf()方法转换一个下,这是一个创建数据的方法,具体的可以参考一下kotlin的文档。

       注意一下 SpringApplication.run中参数这个和java的区别有点大
 
Application.kt类代码
 
package demo

import org.springframework.boot.SpringApplication
@RestController
@SpringBootApplication
class Application{

@RequestMapping(value = "/hello",method =arrayOf(RequestMethod.GET))
fun hello(): String {

return "hello kotlin";

}
}

fun main(args: Array<String>){

//::符号是得到这个类的class对象
SpringApplication.run(Application::class.java,*args);

}3.项目基本搭建完成,试试启动项目访问http://localhost:8090/demo/hello,页面会返回hello kotlin。





 
 
  查看全部
       本文的组要目的是完成SpringBoot集成Kotlin的一个基本项目构建,通过这个例子能够对kotlin有一个简单的了解。与其看着枯燥的教程,看看它的使用也许会更有意思。

kotlin简介
      Kotlin是一个基于JVM的编程语言,由JetBrains设计开发并开源。Kotlin可以编译成Java字节码也可以编译成JavaScript,支持开发Android,并且谷歌已经明确将Kotlin作为Android的一级开发语言。最新的Spring5版本也专门引入了对于Kotlin的支持。Kotlin拥有更简洁的代码,完全兼容java,而且同java可以实现完全的互调。使用Kotlin你起码可以少些30%的代码
 
要求
  • JDK 1.8
  • maven构建
  • Spring4
  • IDEA Intellij
  • Kotlin 1.2.31

 
快速构建
 
首先构建一个maven项目,我们命名为KotlinDemo。(使用idea构建Kotlin项目需要按照Kotlin的插件。)
1.先来修改pom.xml添加需要使用的依赖。 引入spring-boot-starter-parent,这里使用1.5.6版本
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
添加需要的依赖
 <properties>
<java.version>1.8</java.version>
<mybatis.spring.version>1.2.4</mybatis.spring.version>
<kotlin.compiler.incremental>true</kotlin.compiler.incremental>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<kotlin.version>1.2.31</kotlin.version>
</properties>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jre8</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>${kotlin.version}</version>
</dependency>
在build中添加插件
 
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>1.2.31</version>
<configuration>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
<jvmTarget>1.8</jvmTarget>
</configuration>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>1.2.31</version>
</dependency>
</dependencies>
</plugin>
2.创建application.yml
server:
context-path: /kotlin
port: 8090
3.创建Application.kt文件
 
       创建类的方法同java相似,也是引入各种包,但是需要注意Kotlin的main方法是class外面和java的main方法区别

        添加spring的注解@RestController和@SpringBootApplication,我们在class里面创建一个简单的restfull格式的请求方法hello(),方法返一个String的字符串。

       添加@RequestMapping时候需要注意设置method的时候,这里method接收的是一个数组,不是RequestMethod.GE,所以我们需要通过kotlin提供的arrayOf()方法转换一个下,这是一个创建数据的方法,具体的可以参考一下kotlin的文档。

       注意一下 SpringApplication.run中参数这个和java的区别有点大
 
Application.kt类代码
 
package demo

import org.springframework.boot.SpringApplication
@RestController
@SpringBootApplication
class Application{

@RequestMapping(value = "/hello",method =arrayOf(RequestMethod.GET))
fun hello(): String {

return "hello kotlin";

}
}

fun main(args: Array<String>){

//::符号是得到这个类的class对象
SpringApplication.run(Application::class.java,*args);

}
3.项目基本搭建完成,试试启动项目访问http://localhost:8090/demo/hello,页面会返回hello kotlin。

a.png