springboot: mybatis的使用

第一步:引入mybatis依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.0</version>
</dependency>
<dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.10</version>
</dependency>
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.28</version><scope>runtime</scope>
</dependency>
<dependency><groupId>javax.persistence</groupId><artifactId>persistence-api</artifactId><version>1.0</version>
</dependency>

第二步:类目表实体类

package com.payease.dataobject;import lombok.Data;
import org.hibernate.annotations.DynamicUpdate;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;/*** @Created By Maynard.ran* @CreateTime 2021/07/05 下午6:13**/@Entity
@DynamicUpdate   //动态时间修改
@Data            // get set toString 登方法
public class ProductCategory {/** 类目id. */@Id@GeneratedValueprivate Integer categoryId;/** 类目名字. */private String categoryName;/** 类目编号. */private Integer categoryType;//    private Date createTime;
//
//    private Date updateTime;public ProductCategory() {}public ProductCategory(String categoryName, Integer categoryType) {this.categoryName = categoryName;this.categoryType = categoryType;}
}

第三步:编写相应的mapper文件

package com.payease.dataobject.mapper;import com.payease.dataobject.ProductCategory;
import org.apache.ibatis.annotations.*;import java.util.List;
import java.util.Map;/*** @Created By Maynard.ran* @CreateTime 2021/07/05 下午6:13**/public interface ProductCategoryMapper {/*** 通过参数为map保存* @param map* @return*/@Insert("insert into product_category(category_name, category_type) values (#{category_name , jdbcType=VARCHAR}, #{category_type, jdbcType=INTEGER})")int insertByMap(Map<String, Object> map);/*** 通过参数为对象保存* @param productCategory* @return*/@Insert("insert into product_category(category_name, category_type) values (#{categoryName , jdbcType=VARCHAR}, #{categoryType, jdbcType=INTEGER})")int insertByObject(ProductCategory productCategory);/*** 查单一数据* 通过categoryType查询product_category表 @Result注解设置返回值* @param categoryType* @return*/@Select("select * from product_category where category_type = #{categoryType}")@Results({@Result(column = "category_id", property = "categoryId"),@Result(column = "category_name", property = "categoryName"),@Result(column = "category_type", property = "categoryType")})ProductCategory findByCategoryType(Integer categoryType);/*** 查集合* 通过categoryName查询product_category表 @Result注解设置返回值* @param categoryName* @return*/@Select("select * from product_category where category_name = #{categoryName}")@Results({@Result(column = "category_id", property = "categoryId"),@Result(column = "category_name", property = "categoryName"),@Result(column = "category_type", property = "categoryType")})List<ProductCategory> findByCategoryName(String categoryName);/*** 根据某个字段更新* 通过查询category_type 来修改 category_name* @param categoryName* @param categoryType* @return*/@Update("update product_category set category_name = #{categoryName} where category_type = #{categoryType}")int updateByCategoryType(@Param("categoryName") String categoryName,@Param("categoryType") Integer categoryType);/*** 根据对象更新* 通过查询category_type 来修改 category_name* @param productCategory* @return*/@Update("update product_category set category_name = #{categorName} where category_type = #{categoryType}")int updateByObject(ProductCategory productCategory);/*** 根据某个字段来删除数据* 通过category_type 来删除数据* @param categoryType* @return*/@Delete("delete from product_category where category_type = #{categoryType}")int deleteByCategoryType(Integer categoryType);/*** mybatis xml的使用样例* 通过categoryType 查询数据* @param categoryType* @return*/ProductCategory selectByCategoryType(Integer categoryType);
}

第四步:测试类的编写

package com.payease.dataobject.mapper;import com.payease.dataobject.ProductCategory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** @Created By Maynard.ran* @CreateTime 2021/07/05 下午6:13**/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductCategoryMapperTest {@Autowiredprivate ProductCategoryMapper mapper;@Testpublic void insertByMap() throws Exception {Map<String, Object> map = new HashMap<>();map.put("category_name","吃鸡专属");map.put("category_type",103);int result = mapper.insertByMap(map);Assert.assertEquals(1,result);}@Testpublic void insertByObject() throws Exception {ProductCategory productCategory = new ProductCategory();productCategory.setCategoryName("大吉大利");productCategory.setCategoryType(102);int result = mapper.insertByObject(productCategory);Assert.assertEquals(1,result);}@Testpublic void findByCategoryType() throws Exception{ProductCategory result = mapper.findByCategoryType(102);Assert.assertNotNull(result);}@Testpublic void findByCategoryName() throws Exception{List<ProductCategory> result = mapper.findByCategoryName("吃鸡专属");Assert.assertNotEquals(0,result.size());}@Testpublic void updateByCategoryType(){int result = mapper.updateByCategoryType("绝地求生", 103);Assert.assertEquals(1, result);}@Testpublic void updateByObject(){ProductCategory productCategory = new ProductCategory();productCategory.setCategoryName("今晚吃鸡|大吉大利");productCategory.setCategoryType(102);int result = mapper.updateByObject(productCategory);Assert.assertEquals(1, result);}@Testpublic void deleteByCategoryType(){int result = mapper.deleteByCategoryType(102);Assert.assertEquals(1, result);}@Testpublic void selectByCategoryType(){ProductCategory result = mapper.selectByCategoryType(101);Assert.assertNotNull(result);}}

第五步:启动类上加入mapper扫描注解

package com.payease;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan(basePackages = "com.payease.dataobject.mapper")
public class SellApplication {public static void main(String[] args) {SpringApplication.run(SellApplication.class, args);}
}

第六步:对于mybatis xml文件的使用需要

1.在 resource/mapper文件夹下创建相应的xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.payease.dataobject.mapper.ProductCategoryMapper" ><resultMap id="BaseResultMap" type="com.payease.dataobject.ProductCategory" ><id column="category_id" property="categoryId" jdbcType="INTEGER" /><result column="category_name" property="categoryName" jdbcType="VARCHAR" /><result column="category_type" property="categoryType" jdbcType="INTEGER" /><result column="create_time" property="createTime" jdbcType="TIMESTAMP" /><result column="update_time" property="updateTime" jdbcType="TIMESTAMP" /></resultMap><sql id="base_column" >category_id,category_name,category_type</sql><select id="selectByCategoryType" resultMap="BaseResultMap" parameterType="java.lang.Integer" >select <include refid="base_column" />from product_categorywhere category_type = #{category_type,jdbcType=INTEGER}</select></mapper>

2.在application.yml文件夹下配置xml文件的扫描

注1: mapper文件的使用 封装到dao层

package com.payease.dataobject.dao;import com.payease.dataobject.mapper.ProductCategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;import java.util.Map;/*** @Created By Maynard.ran* @CreateTime 2021/07/05 下午6:13**/
public class ProductCategoryDao {@AutowiredProductCategoryMapper mapper;public int insertByMap(Map<String, Object> map){return mapper.insertByMap(map);}
}

注2:日志查看mapper文件中的SQL语句

这是application.yml文件的配置

spring:datasource:driver-class-name: com.mysql.jdbc.Driverusername: rootpassword: liuxiaoming_123 #1234url: jdbc:mysql://rm-uf6qe0894f7hv8977o.mysql.rds.aliyuncs.com/sell?characterEncoding=utf-8&useSSL=false#url: jdbc:mysql://127.0.0.1/sell?characterEncoding=utf-8&useSSL=falsejpa:show-sql: truejackson:default-property-inclusion: non_nullredis:host: 192.168.1.183port: 6379
server:context-path: /sell
#logging:
#  pattern:
#    console: "%d - %msg%n"  #日志格式 日期 - 信息 空格
#  path: /Users/liuxiaoming/Documents/ideawork/sell_log #日志路径 默认名字spring.log
#  file: /Users/liuxiaoming/Documents/ideawork/sell_log/sell.log #日志文件+路径
#  level:  #日志级别
#    com.payease.LoggerTest: debug #日志级别指定某个类 也可以步制定类 直接在level: 后面配置#日志查看SQL语句
logging:level:com.payease.dataobject.mapper: tracewechat:mpAppId: wxd898fcb01713c658mpAppSecret: 47ccc303338cee6e62894fxxxxxxxxxxxopenAppId: wx6ad144e54af67d87openAppSecret: 91a2ff6d38a2bbccfb7e9f9079108e2emchId: 1483469312mchKey: 06C56A89949D617xxxxxxxxxxxkeyPath: /var/weixin_cert/h5.p12notifyUrl: http://sell.natapp4.cc/sell/pay/notifytemplateId:orderStatus: e-Cqq67QxD6YNI41iRiqawEYdFavW_7pc7LyEMb-yeQ#projectUrl:
#  wechatMpAuthorize: http://sell.natapp4.cc
#  wechatOpenAuthorize: http://sell.natapp4.cc
#  sell: http://sell.natapp4.cc
projectUrl:wechatMpAuthorize: http://127.0.0.1:8080wechatOpenAuthorize: http://127.0.0.1:8080sell: http://127.0.0.1:8080

springboot整合mybatis使用示例相关推荐

  1. mysql+xml+注释,springboot整合mybatis完整示例, mapper注解方式和xml配置文件方式实现(我们要优雅地编程)...

    一.注解方式 pom org.mybatis.spring.boot mybatis-spring-boot-starter 2.0.0 mysql mysql-connector-java org. ...

  2. (一)SpringBoot 整合 MyBatis

    一.工具 IDE:idea.DB:mysql 二.创建SpringBoot工程 在Idea中使用SpringInitializr模板创建SpringBoot工程,依赖选择如下: 这里也可以不选JDBC ...

  3. SpringBoot整合MyBatis与MySql8.0

    一.前言 之前已经有一篇文章讨论过SpringBoot整合MyBatis,因而此篇不在重复累赘,本文主要是最新版的SpringBoot2.0与MyBatis.最新MySQL8.0整合过程中遇到的问题进 ...

  4. SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例(转)...

    SpringBoot整合mybatis.shiro.redis实现基于数据库的细粒度动态权限管理系统实例 shiro 目录(?)[+] 前言 表结构 maven配置 配置Druid 配置mybatis ...

  5. mybatis plugins_[MyBatis] SpringBoot 整合Mybatis

    现在基本上搭建一个简单的工程都是三剑客 springboot+mybatis+redis 之前整合Mybatis 都是按照SSM来,所以,这一次带来SpringBoot+MyBatis 的快速整合 p ...

  6. SpringBoot整合Mybatis超详细流程

    SpringBoot整合Mybatis超详细流程 文章目录 SpringBoot整合Mybatis超详细流程 前言 详细流程 0.引入Mybatis 1.创建数据 2.创建程序目录 3.理解后台访问流 ...

  7. SpringBoot整合Mybatis(高级)

    SpringBoot整合Mybatis(高级) 文章目录 SpringBoot整合Mybatis(高级) 前言 基础环境配置 增删改查 ResultMap 复杂查询 多对一 一对多 动态SQL if ...

  8. 3、SpringBoot整合MyBatis注解版及配置文件版

    目录 1.配置pom.xml 2.配置application.yml 3.配置DruidConfig关联yml的配置文件spring.datasource 4.创建数据库及数据库表结构 5.创建对应的 ...

  9. SpringBoot整合mybatis进行快速开发

    SpringBoot整合mybatis进行数据库操作 1.环境的搭建 pom.xml <!--核心模块,包括自动配置支持.日志和YAML --> <dependencies>& ...

  10. springboot 整合mybatis实现curd

    springboot 整合mybatis pom文件 mvc 架构 application.properties 扩展配置,druid配置类 项目地址: https://github.com/seve ...

最新文章

  1. 多条SQL语句同时执行方法
  2. Activity返回数据给上一个活动
  3. 【方案】0519冰箱运行监测系统:方案分析
  4. Linux:几个重要的文件处理命令
  5. C++ 实例化对象 p-printX()
  6. Linux学习之系统编程篇:ps 和 kill 命令以及父子进程间数据共享模式
  7. Centos7 Git源码安装
  8. Angular @Effect监听指定Action类型的实现原理
  9. GIMP中的新建Layer与更改Layer大小
  10. android ROM ---(1)高通平台 Android O 升级学习
  11. 团队作业——四则运算网页版
  12. php支付自定义金额,自定义付款/支付/收费
  13. 自我提高网站list
  14. 台达PLC与台达DTE8路温控程序,威纶通触摸屏与温控器modbus485通讯
  15. SGD,Momentum,优化算法原理及实现
  16. 《动手学深度学习》组队学习打卡Task5——卷积神经网络进阶
  17. js 根据链接下载 excel 文件
  18. 卸载IE9重装IE9无法安装的原因及解决方法
  19. SEERC 2017 J Cunning Friends
  20. 计算机竞赛一等奖学校名单,信息竞赛获奖名单出炉!这些学校榜上有名

热门文章

  1. R笔记|R包下载命令及自带数据集
  2. 草柴返利APP如何领取天猫淘宝红包优惠券享淘礼金红包0元购物福利?
  3. 喜报!昂视荣获中国工控网第二十届自动化及数字化年度自动化创新奖
  4. mysql中undo空间爆满原因_记一次ORACLE的UNDO表空间爆满分析过程
  5. 分布式搜索引擎Elasticsearch使用小结 1.0
  6. Linux宝塔面板 网址忘记了,或者账号密码错误怎么办?
  7. 清洗管道用超声波震动棒
  8. MPC中是如何显示字幕文件的?
  9. 计算机网络学习日记 Day4----数据链路层
  10. 在Mac上如何使用 “夜览”?