Kotlin + SpringBoot开发(三)

前言

通过Kotlin + SpringBoot开发(二)已经完成了数据库的配置工作,可以进行CRUD的操作了。

CRUD操作

  1. 在DAO层的 UserMapper 中添加 selectAll的代码,代码如下:
/**
 *  用户表 Mapper 接口
 *========================
 * Created with IntelliJ IDEA
 * Author: Mr.Su
 * Blog: https://suzf.top/
 * Date: 2019-10-10
 * ========================
 */
interface UserMapper : BaseMapper<User> {

    /**
     *  查询全部
     */
    fun selectAll(): MutableList<User>

    /**
     *  根据ID查询单个用户
     */
    fun findOneById(@Param("id") id: Int): User?

    /**
     *  根据ID删除单个
     */
    fun deleteById(@Param("id") id: Int)
}
  1. 在resource/mapper的 UserMapper.xml 文件中增加对应的SQL,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="suzf.top.kotlinjava.common.mapper.UserMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="suzf.top.kotlinjava.common.entity.User">
        <id column="id" property="id" />
        <result column="username" property="username" />
        <result column="password" property="password" />
        <result column="role" property="role" />
        <result column="permission" property="permission" />
        <result column="ban" property="ban" />
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, username, password, role, permission, ban
    </sql>

    
    <!-- 查询全部 -->
    <select id="selectAll" resultMap="BaseResultMap">
        select * from user
    </select>

    <!-- 根据ID查询单个 -->
    <select id="findOneById" resultMap="BaseResultMap" parameterType="Integer">
        select * from user where id = #{id}
    </select>

    <!-- 根据ID删除数据 -->
    <delete id="deleteById" parameterType="Integer">
        delete from user where id= #{id}
    </delete>
    
</mapper>

  1. service层的 UserService 服务类中增加查询全部的接口,代码如下:
/**
 *  用户表 服务类
 *========================
 * Created with IntelliJ IDEA
 * Author: Mr.Su
 * Blog: https://suzf.top/
 * Date: 2019-10-10
 * ========================
 */
interface UserService : IService<User> {

    /**
     *  查询全部数据
     */
    fun selectAll(): MutableList<User>

}
  1. 在 serviceImpl 服务实现类实现 selectAll(),代码如下:
/**
 *  用户表 服务实现类
 *========================
 * Created with IntelliJ IDEA
 * Author: Mr.Su
 * Blog: https://suzf.top/
 * Date: 2019-10-10
 * ========================
 */
@Service
class UserServiceImpl : ServiceImpl<UserMapper, User>(), UserService {

    @Resource
    lateinit var userMapper: UserMapper

    /**
     * 查询全部
      */
    override fun selectAll(): MutableList<User> {
        return userMapper.selectAll()
    }

}

  1. 在controller层的 UserController 中增加如下代码:
/**
 *  用户表 前端控制器
 *========================
 * Created with IntelliJ IDEA
 * Author: Mr.Su
 * Blog: https://suzf.top/
 * Date: 2019-10-10
 * ========================
 */
@RestController
@RequestMapping(value = "/user")
class UserController {

    @Autowired
    lateinit var userService: UserService

    @GetMapping(value = "/findAll")
    fun findAll(): RespResult {
        return RespResult(CommonConstant.SUCCESS_CODE, CommonConstant.SUCCESS_MSG, userService.selectAll())
    }

    @GetMapping(value = "/findOneById/{id}")
    fun findOneById(@PathVariable id: Int): RespResult {
        return RespResult(CommonConstant.SUCCESS_CODE, CommonConstant.SUCCESS_MSG, userService.findOneById(id))
    }

    @DeleteMapping(value = "/deleteById/{id}")
    fun deleteById(@PathVariable id: Int): RespResult {
        userService.deleteById(id)
        return RespResult(CommonConstant.SUCCESS_CODE, CommonConstant.SUCCESS_MSG)
    }

    @PostMapping(value = "/insert")
    fun insertUser(@RequestBody user: User): RespResult {
        userService.insertUser(user)
        return RespResult(CommonConstant.SUCCESS_CODE, CommonConstant.SUCCESS_MSG)
    }
}

  1. 启动项目,运行 KotlinJavaApplication.kt ,启动日志如下:
2019-10-12 08:56:28.459  INFO 20860 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/oauth/token'], Ant [pattern='/oauth/token_key'], Ant [pattern='/oauth/check_token']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@70211df5, org.springframework.security.web.context.SecurityContextPersistenceFilter@f4a3a8d, org.springframework.security.web.header.HeaderWriterFilter@178f268a, org.springframework.security.web.authentication.logout.LogoutFilter@17dd671f, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@1a6dc589, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@d613308, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@6920b0bc, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@4c5228e7, org.springframework.security.web.session.SessionManagementFilter@d7109be, org.springframework.security.web.access.ExceptionTranslationFilter@329bad59, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@a4b5ce3]
2019-10-12 08:56:28.471  INFO 20860 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/api/**']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@5d97caa4, org.springframework.security.web.context.SecurityContextPersistenceFilter@16a9eb2e, org.springframework.security.web.header.HeaderWriterFilter@3fba233d, org.springframework.security.web.authentication.logout.LogoutFilter@d1d8e1a, org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter@6c5ddccd, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@76332405, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@187e5235, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@6732726, org.springframework.security.web.session.SessionManagementFilter@427ae189, org.springframework.security.web.access.ExceptionTranslationFilter@4784efd9, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@4c86da0c]
2019-10-12 08:56:28.474  INFO 20860 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@650ae78c, org.springframework.security.web.context.SecurityContextPersistenceFilter@2d64c100, org.springframework.security.web.header.HeaderWriterFilter@47d023b7, org.springframework.security.web.authentication.logout.LogoutFilter@6e6d4780, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@69d45cca, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@2fdf17dc, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@2e73d5eb, org.springframework.security.web.session.SessionManagementFilter@5c83ae01, org.springframework.security.web.access.ExceptionTranslationFilter@4190bc8a]
2019-10-12 08:56:28.739  INFO 20860 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8889 (http) with context path ''
2019-10-12 08:56:28.742  INFO 20860 --- [           main] s.t.kotlinjava.KotlinJavaApplicationKt   : Started KotlinJavaApplicationKt in 4.752 seconds (JVM running for 5.668)
2019-10-12 08:56:28.745  INFO 20860 --- [           main] s.top.kotlinjava.KotlinJavaApplication   : ----------------- kotlin Java 学习程序启动成功 {} --------------

在Postman中进行测试

  • 查询全部

http://localhost:8889/user/findAll

findAll.png

  • 根据ID查询单个

http://localhost:8889/user/findOneById/2

findOneById.png

  • 根据ID删除

http://localhost:8889/user/deleteById/2

deleteById.png 然后执行findAll,无id为2的数据,如下图: findAll.png

  • 增加用户信息

http://localhost:8889/user/insert 注意:执行insert方法时需要在Body中选择JSON,如下图进行数据添加:

insert.png 添加完成数据后点击Send,进行数据请求,请求结果如下: send.png 执行findAll,会增加id为5的数据,如下图: findAll.png

总结:

至此已经完成CRUD的基本操作,需要注意的是 insert 方法,需要设置Header的 Content-Type 为 application/json

源码地址:https://gitee.com/sukaihua/kotlinJava


打开微信扫一扫关注小程序

文章请注明出处:https://www.suzf.top/archives/kotlinJava3

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×