栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Kotlin整合SpringBoot+Mybatis+Redis

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Kotlin整合SpringBoot+Mybatis+Redis

最近在学习kotlin用来开发服务端,习惯Spring全家桶的我,特此记录一下kotlin和平时常用的mybatis,redis的整合。


项目环境:
spring-boot-starter-parent: 2.2.2.RELEASE

kotlin-stdlib-jdk8: 1.6.10

mybatis-spring-boot-starter:2.2.0

tk.mybatis:2.1.5

直接使用idea新建一个maven项目或者建一个java项目

随便取个名字下一步下一步。

打开项目后如果是直接maven项目,需要打开Project Structure手动创建resources文件夹并设置文件夹类型,默认是main/java,可以新增一个kotlin文件夹或者直接修改名字。

项目结构如下

 

 

 接下来导入包,关于kotlin的包,可以手动导入,也可以直接编写一个

KotlinApplication.kt文件后idea会提示是否自动导入kotlin相关pom配置

pom详细配置如下

    
        
        org.springframework.boot
        spring-boot-starter-parent
        2.2.2.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.6.10
        
        true
        2.2.0
        2.1.5
        2.13.1
        2.2.2.RELEASE
        1.2.79
    

    
        
            org.jetbrains.kotlin
            kotlin-stdlib-jdk8
            ${kotlin.version}
        
        
            org.jetbrains.kotlin
            kotlin-test
            ${kotlin.version}
            test
        
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            mysql
            mysql-connector-java
            8.0.16
            runtime
        
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            ${mybatis.boot.version}
        
        
            tk.mybatis
            mapper-spring-boot-starter
            ${mapper.starter.version}
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
            ${redis.version}
        
        
            com.alibaba
            fastjson
            ${fastjson.version}
        
        
            com.fasterxml.jackson.module
            jackson-module-kotlin
            ${jackson.module.kotlin}
        
    

    
        src/main/kotlin
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
            
                org.jetbrains.kotlin
                kotlin-maven-plugin
                ${kotlin.version}
                
                    
                        
                        -Xjsr305=strict
                    
                    
                        
                        spring
                        
                        no-arg
                    
                    
                        
                        
                    
                
                
                    
                        org.jetbrains.kotlin
                        kotlin-maven-allopen
                        ${kotlin.version}
                    
                    
                        org.jetbrains.kotlin
                        kotlin-maven-noarg
                        ${kotlin.version}
                    
                
                
                    
                        compile
                        
                            compile
                        
                    
                    
                        test-compile
                        
                            test-compile
                        
                    
                
            
        
    

启动类上添加相应注解

@MapperScan("org.example.mapper")
@SpringBootApplication
class KotlinApplication {}

fun main(args: Array) {
//    SpringApplication.run(KotlinApplication::class.java, *args)
    runApplication(*args)
}

 编写application.yml文件

server:
  port: 8001
spring:
  application:
    name: KotlinSpringBoot
  #数据库连接信息
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/kotlin_study?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
  #Redis连接信息
  redis:
    host: 127.0.0.1
    port: 6379
    password: 123456
# MyBatis配置
mybatis:
  # 搜索指定包别名
  typeAliasesPackage: org.example.entity
  # 配置mapper的扫描,找到所有的mapper.xml映射文件
  mapperLocations: classpath*:mapper*Mapper.xml
  configuration:
    # 日志
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    # 驼峰        
    map-underscore-to-camel-case: true
# 加载全局的配置文件
#  configLocation: classpath:mybatis/mybatis-config.xml

redis配置

package org.example.config

import com.fasterxml.jackson.annotation.JsonAutoDetect
import com.fasterxml.jackson.annotation.PropertyAccessor
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.cache.annotation.CachingConfigurerSupport
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.connection.RedisConnectionFactory
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer
import org.springframework.data.redis.serializer.StringRedisSerializer


@Configuration
class RedisConfig: CachingConfigurerSupport() {

    @Bean(value = ["redisTemplate"])
    fun redisTemplate(factory : RedisConnectionFactory) : RedisTemplate {
        val mapper = ObjectMapper()
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY)
        val jackson2JsonRedisSerializer = Jackson2JsonRedisSerializer(Any::class.java)
        jackson2JsonRedisSerializer.setObjectMapper(mapper)

        val stringRedisSerializer = StringRedisSerializer()

        val template = RedisTemplate()
        template.setConnectionFactory(factory)
        template.keySerializer = stringRedisSerializer
        template.hashKeySerializer = stringRedisSerializer
        template.valueSerializer = jackson2JsonRedisSerializer
        template.hashValueSerializer = jackson2JsonRedisSerializer
        template.afterPropertiesSet()

        return template
    }

}

 编写controller层,service层,mapper层,entity层

package org.example.entity

import tk.mybatis.mapper.annotation.KeySql
import javax.persistence.Id



data class User(

        @Id
        @KeySql(useGeneratedKeys = true)
        var id: Long? = null,
        var name: String = "",
        var age: Int? = 0
)
package org.example.common

import tk.mybatis.mapper.common.ConditionMapper
import tk.mybatis.mapper.common.IdsMapper
import tk.mybatis.mapper.common.Mapper
import tk.mybatis.mapper.common.special.InsertListMapper


interface baseMapper : Mapper, IdsMapper, InsertListMapper, ConditionMapper {
}
package org.example.mapper

import org.apache.ibatis.annotations.Param
import org.apache.ibatis.annotations.Select
import org.example.common.baseMapper
import org.example.entity.User
import org.springframework.stereotype.Component


@Component
interface UserMapper: baseMapper {

    @Select("select * from user where id = #{id}")
    fun findById(@Param("id") id: Long): User

}
package org.example.service

import org.example.entity.User



interface UserService {

    fun findUserById(id: Long): User

    fun findUserAll(): List

    fun insertUser(user: User)
}
package org.example.service.impl

import org.example.entity.User
import org.example.mapper.UserMapper
import org.example.service.UserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service


@Service
class UserServiceImpl : UserService{

    @Autowired
    lateinit var userMapper: UserMapper

    override fun findUserById(id: Long): User {
        return userMapper.findById(id)
    }

    override fun findUserAll(): List {
        return userMapper.selectAll()
    }

    override fun insertUser(user: User) {
        userMapper.insertSelective(user)
    }


}
package org.example.controller

import org.example.entity.User
import org.example.service.UserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.web.bind.annotation.*


@RestController
@RequestMapping("/user")
class UserController {

    @Autowired
    lateinit var userService: UserService

    @Autowired
    lateinit var redisTemplate: RedisTemplate

    @GetMapping("/{id}")
    fun findById(@PathVariable("id") id: Long): User {
        return userService.findUserById(id)
    }

    @GetMapping
    fun findAll(): List {
        return userService.findUserAll()
    }

    @PostMapping
    fun insertUser() {
        val user = User()
        user.age = 13
        user.name = "小王"
        userService.insertUser(user)
    }

    @GetMapping("/redis")
    fun redisOperate(): String {
        var redisKey: String = "Kotlin_study"
        var kotlinRedis: String? = null
        if (redisTemplate.hasKey(redisKey)) {
            kotlinRedis = redisTemplate.opsForValue().get(redisKey).toString()
        } else {
            redisTemplate.opsForValue().set(redisKey, "kotlin redis!")
        }

        return kotlinRedis ?: "没有查询到相关内容"
    }

}

数据库建表

-- auto-generated definition
create table user
(
    id   bigint(9) auto_increment
        primary key,
    name varchar(64)   null,
    age  int           null,
    role int default 0 null comment '0-学生 1-老师'
);

运行一下没有问题

 使用工具测试一下接口

 redis存取正常

 这里顺便推荐一个mybatis日志插件,intellij-mybaitslog GitHub上提供下载,不提供在线仓库安装,和mybatis log plugin相比基本功能一致,但是免费

 参考文章:https://blog.csdn.net/RtxTitanV/article/details/106314300

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/684709.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号