最近在学习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详细配置如下
<parent>
<!-- SpringBoot 起步依赖 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<kotlin.version>1.6.10</kotlin.version>
<!-- 增量编译:为了使构建更快,为Maven启用增量编译 也可以使用 -Dkotlin.compiler.incremental=true 选项运行构建 -->
<kotlin.compiler.incremental>true</kotlin.compiler.incremental>
<mybatis.boot.version>2.2.0</mybatis.boot.version>
<mapper.starter.version>2.1.5</mapper.starter.version>
<jackson.module.kotlin>2.13.1</jackson.module.kotlin>
<redis.version>2.2.2.RELEASE</redis.version>
<fastjson.version>1.2.79</fastjson.version>
</properties>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test</artifactId>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
<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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
<scope>runtime</scope>
</dependency>
<!-- SpringBoot集成mybatis框架 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.boot.version}</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>${mapper.starter.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>${redis.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
<version>${jackson.module.kotlin}</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- kotlin-maven-plugin 插件 -->
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<configuration>
<args>
<!-- 负责检查对JSR-305注解的支持 -->
<arg>-Xjsr305=strict</arg>
</args>
<compilerPlugins>
<!-- Kotlin的类默认都是final的,启用kotlin-spring编译器插件
该插件指定了以下注解:@Component、@Async、@Transactional、@Cacheable以及@SpringBootTest。
由于元注解的支持,标注有@Configuration、@Controller、@RestController、@Service或者@Repository
的类会自动添加open,因为这些注解标注有元注解@Component -->
<plugin>spring</plugin>
<!-- 无参(no-arg)编译器插件为具有特定注解的类生成一个额外的零参数构造函数
这个生成的构造函数是合成的,因此不能从Java或Kotlin中直接调用,但可以使用反射调用。
对于JPA支持用“jpa”插件 -->
<plugin>no-arg</plugin>
</compilerPlugins>
<pluginOptions>
<!-- 指定应用no-arg插件的自定义注解 -->
<option>no-arg:annotation=com.rtxtitanv.annotation.KtNoArgsConstructor</option>
</pluginOptions>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-noarg</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
启动类上添加相应注解
@MapperScan("org.example.mapper") @SpringBootApplication class KotlinApplication {} fun main(args: Array<String>) { // SpringApplication.run(KotlinApplication::class.java, *args) runApplication<KotlinApplication>(*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
/**
* @Author: Lc
* @Description:
* @Date: 2021/12/29 9:36
*/
@Configuration
class RedisConfig: CachingConfigurerSupport() {
@Bean(value = ["redisTemplate"])
fun redisTemplate(factory : RedisConnectionFactory) : RedisTemplate<Any, Any> {
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<Any, Any>()
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
/**
* @Author: Lc
* @Description:
* @Date: 2021/12/28 14:55
*/
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
/**
* @Author: Lc
* @Description:
* @Date: 2021/12/28 15:22
*/
interface BaseMapper<T> : Mapper<T>, IdsMapper<T>, InsertListMapper<T>, ConditionMapper<T> {
}
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
/**
* @Author: Lc
* @Description:
* @Date: 2021/12/28 15:21
*/
@Component
interface UserMapper: BaseMapper<User> {
@Select("select * from user where id = #{id}")
fun findById(@Param("id") id: Long): User
}
package org.example.service
import org.example.entity.User
/**
* @Author: Lc
* @Description:
* @Date: 2021/12/28 15:24
*/
interface UserService {
fun findUserById(id: Long): User
fun findUserAll(): List<User>
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
/**
* @Author: Lc
* @Description:
* @Date: 2021/12/28 15:25
*/
@Service
class UserServiceImpl : UserService{
@Autowired
lateinit var userMapper: UserMapper
override fun findUserById(id: Long): User {
return userMapper.findById(id)
}
override fun findUserAll(): List<User> {
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.*
/**
* @Author: Lc
* @Description:
* @Date: 2021/12/28 14:54
*/
@RestController
@RequestMapping("/user")
class UserController {
@Autowired
lateinit var userService: UserService
@Autowired
lateinit var redisTemplate: RedisTemplate<Any, Any>
@GetMapping("/{id}")
fun findById(@PathVariable("id") id: Long): User {
return userService.findUserById(id)
}
@GetMapping
fun findAll(): List<User> {
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