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详细配置如下

    <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

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Kotlin是一种静态类型的编程语言,具有JVM的可移植性和Java的互操作性。Spring Boot是一个用于创建独立的、基于Spring框架的Java应用程序的框架,它提供了快速开发应用程序所需的所有功能。JavaFX是一个用于创建丰富客户端应用程序的框架,它提供了丰富的UI组件和布局管理器。 要使用Kotlin Spring Boot和JavaFX开发桌面应用程序,需要完成以下步骤: 1. 创建一个Kotlin Spring Boot项目。可以使用Spring Initializr创建项目,选择Kotlin和Spring Web依赖项。 2. 添加JavaFX依赖项。可以在pom.xml文件中添加以下依赖项: ``` <dependency> <groupId>org.openjfx</groupId> <artifactId>javafx-controls</artifactId> <version>16</version> </dependency> <dependency> <groupId>org.openjfx</groupId> <artifactId>javafx-fxml</artifactId> <version>16</version> </dependency> ``` 3. 创建一个JavaFX应用程序类。可以使用JavaFX的Application类作为应用程序的入口点。在这个类中,可以创建UI组件,处理事件和管理应用程序的状态。以下是一个简单的JavaFX应用程序类的示例: ```kotlin import javafx.application.Application import javafx.fxml.FXMLLoader import javafx.scene.Parent import javafx.scene.Scene import javafx.stage.Stage class MyApplication : Application() { override fun start(primaryStage: Stage?) { val root: Parent = FXMLLoader.load(javaClass.getResource("/fxml/main.fxml")) primaryStage?.title = "My Application" primaryStage?.scene = Scene(root) primaryStage?.show() } companion object { @JvmStatic fun main(args: Array<String>) { launch(MyApplication::class.java, *args) } } } ``` 4. 创建FXML布局文件。FXML是一种XML格式的文件,用于定义UI组件和布局。可以使用Scene Builder或手动创建FXML文件。以下是一个简单的FXML布局文件的示例: ```xml <?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.control.Button?> <?import javafx.scene.layout.AnchorPane?> <AnchorPane xmlns:fx="http://javafx.com/fxml/1" fx:id="root" prefHeight="400" prefWidth="600"> <Button fx:id="button" text="Click me" layoutX="250" layoutY="180" /> </AnchorPane> ``` 5. 在JavaFX应用程序类中加载FXML布局文件。可以使用FXMLLoader类加载FXML布局文件,并将其添加到应用程序的场景图中。以下是一个示例: ```kotlin val root: Parent = FXMLLoader.load(javaClass.getResource("/fxml/main.fxml")) primaryStage?.title = "My Application" primaryStage?.scene = Scene(root) primaryStage?.show() ``` 6. 处理UI事件。可以在JavaFX应用程序类中添加事件处理程序,以响应UI组件的事件。以下是一个处理按钮单击事件的示例: ```kotlin button.setOnAction { event -> println("Button clicked!") } ``` 7. 使用Spring Boot管理应用程序的状态。可以使用Spring Boot的依赖注入和管理功能来管理应用程序的状态和依赖关系。可以在Spring Boot的配置类中定义bean,然后在JavaFX应用程序类中使用它们。以下是一个简单的Spring Boot配置类的示例: ```kotlin @Configuration class AppConfig { @Bean fun myService(): MyService { return MyService() } } ``` 8. 在JavaFX应用程序类中使用Spring Boot的依赖注入功能。可以在JavaFX应用程序类的构造函数中注入Spring Boot管理的bean。以下是一个示例: ```kotlin class MyApplication : Application() { @Autowired lateinit var myService: MyService // ... } ``` 这就是使用Kotlin Spring Boot和JavaFX开发桌面应用程序的基本步骤。当然,还有很多其他的细节和技术,可以根据需要进行学习和应用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值