首页 > 其他分享 >springboot 集成jimmer

springboot 集成jimmer

时间:2022-09-07 22:47:08浏览次数:77  
标签:集成 springboot sql springframework org fun import jimmer

添加依赖

plugins {
    // 第一步: 添加ksp插件
    id("com.google.devtools.ksp") version "1.7.10-1.0.6"

    ...ommit other plugins...
}
depdencies {
    
    // 第二步: 添加jimmer-sql-kotlin
    implementation("org.babyfish.jimmer:jimmer-sql-kotlin:0.1.30")

    // 第三步: 应用ksp插件
    ksp("org.babyfish.jimmer:jimmer-ksp:0.1.30")

    runtimeOnly("com.h2database:h2:2.1.212")

    ...ommit other dependency...
}

// 第四步: 讲生成的代码添加到编译目录中。
// 没有这个配置,gradle命令仍然可以正常执行,
// 但是, Intellij无法找到生成的源码。
kotlin {
    sourceSets.main {
        kotlin.srcDir("build/generated/ksp/main/kotlin")
    }
}

配置

yaml配置

spring:
  application:
    name: jimmer-demo
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost/sbfzl?serverTimezone=GMT%2B8
    username: root
    password: root

server:
  port: 8080

配置类

  • json序列化配置

    import com.fasterxml.jackson.databind.ObjectMapper
    import com.fasterxml.jackson.databind.ObjectWriter
    import org.babyfish.jimmer.jackson.ImmutableModule
    import org.springframework.context.annotation.Bean
    import org.springframework.context.annotation.Configuration
    
    @Configuration
    class JacksonConfig {
    
        @Bean
        fun prettyWriter(): ObjectWriter {
            return ObjectMapper()
                .registerModule(ImmutableModule())
                .writerWithDefaultPrettyPrinter()
        }
    
    	// 这个必不可少
        @Bean
        fun setImmutableMode(): ObjectMapper {
            return ObjectMapper()
                .registerModule(ImmutableModule())
        }
    }
    
  • SqlClient配置

    import org.babyfish.jimmer.sql.dialect.MySqlDialect
    import org.babyfish.jimmer.sql.kt.KSqlClient
    import org.babyfish.jimmer.sql.kt.newKSqlClient
    import org.slf4j.LoggerFactory
    import org.springframework.beans.factory.annotation.Value
    import org.springframework.context.annotation.Bean
    import org.springframework.context.annotation.Configuration
    import org.springframework.jdbc.datasource.DataSourceUtils
    import java.sql.Connection
    import javax.sql.DataSource
    
    @Configuration
    class SqlClientConfig {
    
        private val LOGGER = LoggerFactory.getLogger(SqlClientConfig::class.java)
    
        @Bean
        fun sqlClient(
            dataSource: DataSource,
            @Value("\${spring.datasource.url}") jdbcUrl: String,
        ): KSqlClient = newKSqlClient {
            setConnectionManager {
                /*
                 * It's very important to use
                 *      "org.springframework.jdbc.datasource.DataSourceUtils"!
                 * This is spring transaction aware ConnectionManager
                 */
                val con: Connection = DataSourceUtils.getConnection(dataSource)
                try {
                    proceed(con)
                } finally {
                    DataSourceUtils.releaseConnection(con, dataSource)
                }
            }
            setExecutor {
                /*
                 * Log SQL and variables
                 */
                LOGGER.info("Execute sql : \"{}\", with variables: {}", sql, variables)
                proceed()
            }
            setDialect(MySqlDialect())
        }
    }
    

业务代码

通用返回结果集

data class R (
    val code: Int,
    val message: String,
    val data: Any?,
) {
    companion object {
        fun ok() = R(200, "success", null)
        fun fail() = R(500, "failure", null)
    }
    fun body(elem: Any?) = this.copy(data = elem)
}

数据实体类

import org.babyfish.jimmer.sql.Entity
import org.babyfish.jimmer.sql.GeneratedValue
import org.babyfish.jimmer.sql.Id
import org.babyfish.jimmer.sql.Table
import org.babyfish.jimmer.sql.meta.IdentityIdGenerator

@Entity
@Table(name = "t_user")
interface TUser {
    @GeneratedValue(generatorType = IdentityIdGenerator::class)
    @Id
    val id: Long
    val username: String
    val password: String
}

基础CRUD

  • controller

    import com.example.dfgfdafgadgdg.service.UserService
    import com.example.dfgfdafgadgdg.common.R
    import com.example.dfgfdafgadgdg.model.TUser
    import org.springframework.web.bind.annotation.DeleteMapping
    import org.springframework.web.bind.annotation.GetMapping
    import org.springframework.web.bind.annotation.PathVariable
    import org.springframework.web.bind.annotation.PostMapping
    import org.springframework.web.bind.annotation.PutMapping
    import org.springframework.web.bind.annotation.RequestBody
    import org.springframework.web.bind.annotation.RequestMapping
    import org.springframework.web.bind.annotation.RestController
    
    @RestController
    @RequestMapping("user")
    class UserController(
        private val userService: UserService
    ) {
        @GetMapping
        fun get() = R.ok().body(userService.selectAll())
    
        @GetMapping("{id}")
        fun getById(@PathVariable("id") id: Int) = R.ok().body(userService.selectById(id))
    
        @PostMapping
        fun add(@RequestBody user: TUser) = R.ok().body(userService.insert(user))
    
        @PutMapping
        fun update(@RequestBody user: TUser) = R.ok().body(userService.update(user))
    
        @DeleteMapping("{id}")
        fun remove(@PathVariable("id") id: Int) = R.ok().body(userService.delete(id))
    }
    
  • service

    package com.example.dfgfdafgadgdg.service
    
    import com.example.dfgfdafgadgdg.model.TUser
    import org.babyfish.jimmer.sql.kt.KSqlClient
    import org.springframework.stereotype.Service
    
    @Service
    class UserService(
        private val sqlClient: KSqlClient
    ) {
        fun selectAll() = sqlClient
            .createQuery(TUser::class) {
                select(table)
            }.execute()
    
        fun selectById(id: Int) = sqlClient
            .entities.findById(TUser::class, id)
    
    
        fun insert(user: TUser) = sqlClient
            .entities
            .save(user)
    
        fun update(user: TUser) = sqlClient
            .entities
            .save(user)
    
        fun delete(id: Int) = sqlClient
            .entities.delete(TUser::class, id)
    }
    

标签:集成,springboot,sql,springframework,org,fun,import,jimmer
From: https://www.cnblogs.com/poifa/p/16667568.html

相关文章

  • SpringBoot中ElaticSearch工具类-附源码
    importorg.apache.http.HttpHost;importorg.elasticsearch.client.RestClient;importorg.elasticsearch.client.RestHighLevelClient;importorg.springframework.c......
  • 04-配置开发环境(IDEA集成git)
    我经历了一天又一天,才发现明天过了还是明天。未来太远,我看不见。maven使用3.6.3配置aliyun地址<mirrors> <mirror> <id>nexus-aliyun</id> <mirrorOf>......
  • SpringBoot + Caffeine实现本地缓存(内存缓存)
    1.Caffeine简介  Caffeine是一个基于Java8开发的提供了近乎最佳命中率的高性能的缓存库。借鉴GoogleGuava和ConcurrentLinkedHashMap的经验,实现内存缓存。  缓存和......
  • springboot集成ehcache
    目录springboot集成ehcache1、增加依赖2、增加ehcache.xml3、增加配置3.1、bootstrap.propertiesxml3.2、启动类增加配置4、工具类操作5、使用springboot集成ehcacheps:......
  • springboot通过注解Resource引用指定配置
    yaml配置文件中增加两个不同环境的配置:java配置文件,参考微信支付的代码:/***@author<ahref="https://github.com/binarywang">BinaryWang</a>*/@Slf4j@Config......
  • springboot的日志配置
    转载:https://blog.csdn.net/tz845195485/article/details/123361895#========================logging日志相关的配置=====================#日志级别trace<debug<inf......
  • SpringBoot解决BigDecimal传到前端后精度丢失问题
    1、局部处理(1)在相应字段上加@JsonFormat@JsonFormat(shape=JsonFormat.Shape.STRING)(2)在相应字段上加@JsonSerialize@JsonSerialize(using=ToStringSerializer.class......
  • 集成SwiftGen图片资源管理器
    1.cocoapods导入pod'SwiftGen'2.新增js脚本,在TARGETS-BuildPhaes-NewRunScriptPhase3.导入下方js语句if[[-f"${PODS_ROOT}/SwiftGen/bin/swiftgen"]];t......
  • 【AR Engine】集成AR Engine,ARSession.update方法抛出ARFatalException
    ​【问题描述】在App中接入了AREngine,在日志监控中发现个别终端用户在程序调用ARSession.update方法时,AREngine抛出了ARFatalException。通过查看日志发现,这个问题在此......
  • Simulink集成模型测试太慢怎么办?
    Tips:现阶段模型开发大部分采用Simulink,为了验证模型实现了相关功能,需要对模型进行测试。模型测试(MiL)有单元测试和集成测试之分。单元测试中模型复杂度低,信号参数数量少,测......