我们知道,在 MyBatis 中直接 DTO 映射查询的时候,写起来非常简单。只要字段对应上即可:
下面是对应的 Java 代码实例:
package com.alibaba.microtek.mapper.microtek;import com.alibaba.microtek.dto.SlowSqlTemplateDto;import com.alibaba.microtek.model.microtek.XxptSlowQueyInfo;import com.taobao.pandora.pandolet.annotation.Service;import org.apache.ibatis.annotations.ResultType;import org.apache.ibatis.annotations.Select;import java.util.List;public interface XxptSlowQueyInfoMapper { @Select("SELECT app_name appName,sum(slow_template_count) c FROM `xxpt_slow_quey_info` GROUP BY app_name ORDER BY c desc limit 10") @ResultType(SlowSqlTemplateDto.class) List<SlowSqlTemplateDto> listSlowSqlTemplateDto(); }package com.alibaba.microtek.dto;public class SlowSqlTemplateDto { String appName; Integer c; public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public Integer getC() { return c; } public void setC(Integer c) { this.c = c; } }
在 JPA 中,稍微有点费事,但也还好。下面是一个完整的 Kotlin 代码实例
package com.slow.sql.speedoimport org.springframework.beans.factory.annotation.Autowiredimport org.springframework.web.bind.annotation.GetMappingimport org.springframework.web.bind.annotation.RestController@RestControllerclass XxptSlowQueyInfoController { @Autowired lateinit var syncSlowSqlDataJob: SyncSlowSqlDataJob @Autowired lateinit var xxptSlowQueyInfoDao: XxptSlowQueyInfoDao @GetMapping("/syncSlowSqlDataJob") fun syncSlowSqlDataJob() { syncSlowSqlDataJob.sync() } @GetMapping("/listSlowSqlTemplateDto") fun listSlowSqlTemplateDto(): List<SlowSqlTemplateDto> { return xxptSlowQueyInfoDao.listSlowSqlTemplateDto() } }package com.slow.sql.speedoimport org.springframework.data.jpa.repository.JpaRepositoryimport org.springframework.data.jpa.repository.Queryinterface XxptSlowQueyInfoDao : JpaRepository<XxptSlowQueyInfo, Long> { fun save(record: XxptSlowQueyInfo): XxptSlowQueyInfo @Query(""" SELECT new com.slow.sql.speedo.SlowSqlTemplateDto( x.appName , sum(x.slowTemplateCount) ) FROM XxptSlowQueyInfo x GROUP BY x.appName ORDER BY sum(x.slowTemplateCount) desc """) fun listSlowSqlTemplateDto(): List<SlowSqlTemplateDto> }package com.slow.sql.speedoimport com.alibaba.fastjson.annotation.JSONFieldimport java.util.*import javax.persistence.*@Entity@Table(name = "xxpt_slow_quey_info")class XxptSlowQueyInfo { @GeneratedValue(strategy = GenerationType.AUTO) @Id var id: Long? = null @JSONField(name = "app_name") var appName: String? = null var owner: String? = null var ops: String? = null @JSONField(name = "need_optimize_slow_template_count") var needOptimizeSlowTemplateCount: Int? = null @JSONField(name = "need_optimize_slow_sql_count") var needOptimizeSlowSqlCount: Int? = null @JSONField(name = "slow_template_count") var slowTemplateCount: Int? = null @JSONField(name = "slow_sql_count") var slowSqlCount: Int? = null var date: Date? = null}
作者:一个会写诗的程序员
链接:https://www.jianshu.com/p/920e8f1a2dbb