Spring Boot Mybatis简单使用


步骤说明

  • build.gradle:依赖添加
  • application.properties:配置添加
  • 代码编写
  • 测试

build.gradle:依赖添加

    需要添加下面三个依赖:

dependencies {implementation 'org.springframework.boot:spring-boot-starter-data-jpa'implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.0'implementation 'mysql:mysql-connector-java'
}

application.properties:配置添加

    配置文件的编写需要注意参数的配置,比如SSL那个一般要设置为false,driver-class-name也要注意一下,不要写错了,文件的大致内容如下:

mybatis.type-aliases-package=com.seckill.spring.mapperspring.datasource.url=jdbc:mysql://10.33.8.189:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

代码编写

    在入口函数添加Mapper扫描配置,这样不必在每个Mapper上加上Mapper注解,大致如下:

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

    编辑商品实体类,大致如下:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.Size;@Entity
public class Goods {public Goods(int id, String name, int amount) {this.id = id;this.name = name;this.amount = amount;}@Id@GeneratedValue(strategy = GenerationType.AUTO)private int id;@Size(min = 1, max = 50)private String name;private int amount;
}

    编写Mapper接口类,大致内容如下:

import com.seckill.spring.entity.Goods;
import org.apache.ibatis.annotations.*;import java.util.List;public interface GoodsMapper {@Insert("INSERT INTO goods(name, amount) VALUES('${name}', #{amount})")Integer insertGoods(@Param("name")String name, @Param("amount")Integer amount) throws Exception;@Select("SELECT * FROM goods")List<Goods> findAll();@Select("SELECT * FROM goods WHERE id = #{id}")Goods findById(@Param("id") Integer id);@Update("UPDATE goods SET amount = #{goods.amount} WHERE id = #{goods.id}")Integer updateGoods(@Param("goods") Goods goods) throws Exception;@Delete("Delete FROM goods")Integer deleteAll();
}

    其中要注意的是$和#的用法,前者用于字符串变量,后者用于整型变量

// This example creates a prepared statement, something like select * from teacher where name = ?;
@Select("Select * from teacher where name = #{name}")
Teacher selectTeachForGivenName(@Param("name") String name);// This example creates n inlined statement, something like select * from teacher where name = 'someName';
@Select("Select * from teacher where name = '${name}'")
Teacher selectTeachForGivenName(@Param("name") String name);

测试

    测试还有些坑,不如类上面的注解应该如代码中的那样才有用,并且有时发现不了测试函数,需要去掉@Test注解,再重新添加后运行。大致打代码如下:

import com.seckill.spring.Application;
import com.seckill.spring.entity.Goods;
import com.seckill.spring.mapper.GoodsMapper;
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.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class,webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT
)
@DirtiesContext
public class GoodsMapperTest {@Autowiredprivate GoodsMapper goodsMapper;@Testpublic void testAll() throws Exception {goodsMapper.deleteAll();Assert.assertEquals(0, goodsMapper.findAll().size());Integer response = goodsMapper.insertGoods("good1", 1000);Assert.assertEquals(1, response.intValue());List<Goods> goods = goodsMapper.findAll();Assert.assertEquals(1, goods.size());int id = goods.get(0).getId();Assert.assertNotNull(goodsMapper.findById(id));Goods newGoods = new Goods(id, "good1", 100);Assert.assertEquals(1, goodsMapper.updateGoods(newGoods).intValue());Assert.assertEquals(100, goodsMapper.findById(id).getAmount());}
}

参考链接

  • Spring boot 启动报错-Reason Failed to determine a suitable driver class
  • java连接mysql失败Path does not chain with any of the trust anchors
  • SpringBoot+Mybatis框架项目的单元测试和集成测试(下)
  • Spring Boot(六):如何优雅的使用 Mybatis

Spring Boot Mybatis简单使用相关推荐

  1. 最全的Spring Boot +Mybatis 简单的增删查改

    在resources包下创建mapping包然后创建UserMapper.xml UserMapper.xml <?xml version="1.0" encoding=&q ...

  2. spring boot+mybatis整合

    LZ今天自己搭建了下Spring boot+Mybatis,比原来的Spring+SpringMVC+Mybatis简单好多.其实只用Spring boot也可以开发,但是对于多表多条件分页查询,Sp ...

  3. Spring boot Mybatis 整合(注解版)

    之前写过一篇关于springboot 与 mybatis整合的博文,使用了一段时间spring-data-jpa,发现那种方式真的是太爽了,mybatis的xml的映射配置总觉得有点麻烦.接口定义和映 ...

  4. Spring Boot + Mybatis 快速整合

    引言 最近在工作结束后抽时间学习了一下mybatis的知识,因为之前有学习过,但是经久不用,也未曾踏实地整理,因此有所淡忘. super meeting会议管理系统是我厂最近开发的一套会议预约平台.持 ...

  5. spring boot + mybatis + layui + shiro后台权限管理系统

    后台管理系统 版本更新 后续版本更新内容 链接入口: springboot + shiro之登录人数限制.登录判断重定向.session时间设置:https://blog.51cto.com/wyai ...

  6. 从零搭建一个 Spring Boot 开发环境!Spring Boot+Mybatis+Swagger2 环境搭建

    从零搭建一个 Spring Boot 开发环境!Spring Boot+Mybatis+Swagger2 环境搭建 本文简介 为什么使用Spring Boot 搭建怎样一个环境 开发环境 导入快速启动 ...

  7. Spring boot Mybatis 整合(完整版)

    Spring boot Mybatis 整合(完整版) 更多干货 SpringBoot系列目录 正题 本项目使用的环境: 开发工具:Intellij IDEA 2017.1.3 springboot: ...

  8. mysql快速启动_GitHub - TianSiQiang/Spring-Boot-MyBatis-Mysql: Spring Boot+MyBatis+Mysql 快速启动示例...

    Spring Boot+MyBatis+Mysql 添加依赖 引入 lombok.mysql-connector-java .mybatis-plus-boot-starter 依赖: org.pro ...

  9. 第七章、Spring Boot MyBatis升级篇

    课时二十七.Spring Boot MyBatis升级篇-注解 缘起:在一节视频中,有这么一段留言:"会不会推出SpringBoot整合Mybaits配置文件sqlMapConfig.xml ...

最新文章

  1. R语言ggplot2可视化水平条形图的标题(title)、副标题(subtitle)和图片说明信息(caption)左对齐实战
  2. winform 异步弹窗窗体_玩转控件:重写/重绘Dev中MessageBox弹窗控件
  3. 安天移动安全:Janus高危漏洞深度分析
  4. parallels desktop虚拟机与Mac共享网络设置方法
  5. GalleryView
  6. excel使用MySQL数据,如何使用mysql完成excel中的数据生成
  7. [你必须知道的.NET]第二十五回:认识元数据和IL(中)
  8. LINQ TO SQL和Entity Framework 的关系 你了解多少?
  9. 使用.NET Core 3.1构建Windows Worker服务以删除文件夹中的旧文件
  10. vue脚手架的自定义配置
  11. Unity3D 一些工具总结
  12. alios是安卓吗_鸿蒙OS系统被质疑,谷歌也有新布局!阿里云OS事件会再现吗?
  13. java处理网络数据流
  14. 服务器摆放需要预留U位么_让客厅大一倍的小户型沙发摆放技巧,赶快收藏好!
  15. 342. 道路与航线
  16. 机器人行业最新年度预测出炉:中国仍是需求大国,强调全球联动合作
  17. Blender 画正四面体
  18. linux查看msg内容,如何打开MSG文件,如何转换MSG文件
  19. Proxy用法——让我们创建一个API代理器
  20. C语言可以敲哪些小游戏,C语言可以写哪些小游戏?

热门文章

  1. iOS相同字符串保存地址唯一
  2. 在Android中调用KSOAP2库访问webservice服务出现的服务端传入参数为null的问题解决
  3. vs2015打开慢的解决方法
  4. 【干货】智能汽车行业“十年十大预测”.pdf(附下载链接)
  5. 超值赛题分享大礼包,你的“六一”礼物来咯!
  6. linux虚拟机怎么显示桌面,虚拟机中如何开启Linux的3d特效桌面?
  7. Leetcode每日一题:35.search-insert-position(搜索插入位置)
  8. c++中queue用法
  9. 首轮超巨诞生!利拉德轰50分送超远三分压哨绝杀 开拓者4-1淘汰雷霆
  10. 深度学习——卷积神经网络CNN