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.mapper

spring.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 {
@Autowired
private GoodsMapper goodsMapper; @Test
public 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 Mybatis简单使用的更多相关文章

  1. 快速搭建一个Spring Boot + MyBatis的开发框架

    前言:Spring Boot的自动化配置确实非常强大,为了方便大家把项目迁移到Spring Boot,特意总结了一下如何快速搭建一个Spring Boot + MyBatis的简易文档,下面是简单的步 ...

  2. Spring Boot + Mybatis + Redis二级缓存开发指南

    Spring Boot + Mybatis + Redis二级缓存开发指南 背景 Spring-Boot因其提供了各种开箱即用的插件,使得它成为了当今最为主流的Java Web开发框架之一.Mybat ...

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

    个人开源项目 springboot+mybatis+thymeleaf+docker构建的个人站点开源项目(集成了个人主页.个人作品.个人博客) 朋友自制的springboot接口文档组件swagge ...

  4. Spring Boot项目简单上手+swagger配置+项目发布(可能是史上最详细的)

    Spring Boot项目简单上手+swagger配置 1.项目实践 项目结构图 项目整体分为四部分:1.source code 2.sql-mapper 3.application.properti ...

  5. Spring Boot + MyBatis + Druid + Redis + Thymeleaf 整合小结

    Spring Boot + MyBatis + Druid + Redis + Thymeleaf 整合小结 这两天闲着没事想利用**Spring Boot**加上阿里的开源数据连接池**Druid* ...

  6. Spring boot Mybatis整合构建Rest服务(超细版)

     Springboot+ Mybatis+MySql整合构建Rest服务(涵盖增.删.改.查) 1.概要 1.1 为什么要使用Spring  boot? 1.1.1 简单方便.配置少.整合了大多数框架 ...

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

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

  8. (45). Spring Boot MyBatis连接Mysql数据库【从零开始学Spring Boot】

    大家在开发的时候,会喜欢jdbcTemplate操作数据库,有喜欢JPA操作数据库的,有喜欢MyBatis操作数据库的,对于这些我个人觉得哪个使用顺手就使用哪个就好了,并没有一定要使用哪个,个人在实际 ...

  9. Spring Boot MyBatis 数据库集群访问实现

    Spring Boot MyBatis 数据库集群访问实现 本示例主要介绍了Spring Boot程序方式实现数据库集群访问,读库轮询方式实现负载均衡.阅读本示例前,建议你有AOP编程基础.mybat ...

随机推荐

  1. Spring入门篇——第6章 Spring AOP的API介绍

    第6章 Spring AOP的API介绍 主要介绍Spring AOP中常用的API. 6-1 Spring AOP API的Pointcut.advice概念及应用 映射方法是sa开头的所有方法 如 ...

  2. EasyLogging++学习笔记(1)—— 简要介绍

    对于有开发经验的程序员来说,记录程序执行日志是一件必不可少的事情.通过查看和分析日志信息,不仅可以有效地帮助我们调试程序,而且当程序正式发布运行之后,更是可以帮助我们快速.准确地定位问题.在现在这个开 ...

  3. Laravel 多态关联中利用关联表相关字段进行排序的问题

    1 目标 1.1 在 Laravel 项目的开发中,多态的需求很常见,按多态关联进行排序的需求也是必须的. 1.2 请想像,我们有一个需求,荣誉栏目多态关联一个档案模型,要求在荣誉中按档案的推荐时间进 ...

  4. CSP-S 模拟测试 51 题解

    考试过程: 惯例先看一遍三道题,T1 一开始反应要求割点,但是这是有向图,肯定不能求割点,康了一下数据范围,有40%是树的,还不错,决定待会在打. 看T2 字符串题,完了我字符串最弱了,肯定只能打暴力 ...

  5. 前端导出pdf

    html2canvas文档地址 http://html2canvas.hertzen.com/configuration 方式一:使用html2canvas和jspdf插件实现 该方式是通过html2 ...

  6. 初学c++动态联编

    先看一下什么是C++联编? 我觉得通俗的讲,用对象来访问类的成员函数就是静态联编. 那什么是动态联编: 一般是通过虚函数实现动态联编. 看一个动态联编的例子: 我比较懒,所以直接粘贴了MOOC视频的图 ...

  7. UOJ社区版安装多个Judger

    目录 声明 在同一台机器上安装 在不同机子上安装 声明 本文档非官方文档,为我试坑的经验总结. 本文编写时间 2019.11.04 ,并不一定会随UOJ更新而更新. 由于UOJ需要用SVN传题,并不那 ...

  8. 两个int值相乘超过int最大值

    System.out.println(100000000*1000 ); //输出结果是:1215752192 先将100000000*1000 的结果转化为二进制: 10111 01001000 0 ...

  9. Leetcode题目79.单词搜索(回溯+DFS-中等)

    题目描述: 给定一个二维网格和一个单词,找出该单词是否存在于网格中. 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格.同一个单元格内的字母不允许 ...

  10. OUC_TeamTraining_#1 720

    D - The Mirror of Galadriel Time Limit:2000MS     Memory Limit:0KB     64bit IO Format:%lld & %l ...