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

搭建完成简单的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来调试接口。
1.png 2.png 4.png 3.png 5.png

0 个评论

要回复文章请先登录注册