Spring Boot Mybatis简单使用
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 启动报错-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简单使用的更多相关文章
- 快速搭建一个Spring Boot + MyBatis的开发框架
前言:Spring Boot的自动化配置确实非常强大,为了方便大家把项目迁移到Spring Boot,特意总结了一下如何快速搭建一个Spring Boot + MyBatis的简易文档,下面是简单的步 ...
- Spring Boot + Mybatis + Redis二级缓存开发指南
Spring Boot + Mybatis + Redis二级缓存开发指南 背景 Spring-Boot因其提供了各种开箱即用的插件,使得它成为了当今最为主流的Java Web开发框架之一.Mybat ...
- Spring boot Mybatis 整合(完整版)
个人开源项目 springboot+mybatis+thymeleaf+docker构建的个人站点开源项目(集成了个人主页.个人作品.个人博客) 朋友自制的springboot接口文档组件swagge ...
- Spring Boot项目简单上手+swagger配置+项目发布(可能是史上最详细的)
Spring Boot项目简单上手+swagger配置 1.项目实践 项目结构图 项目整体分为四部分:1.source code 2.sql-mapper 3.application.properti ...
- Spring Boot + MyBatis + Druid + Redis + Thymeleaf 整合小结
Spring Boot + MyBatis + Druid + Redis + Thymeleaf 整合小结 这两天闲着没事想利用**Spring Boot**加上阿里的开源数据连接池**Druid* ...
- Spring boot Mybatis整合构建Rest服务(超细版)
Springboot+ Mybatis+MySql整合构建Rest服务(涵盖增.删.改.查) 1.概要 1.1 为什么要使用Spring boot? 1.1.1 简单方便.配置少.整合了大多数框架 ...
- Spring boot Mybatis 整合(注解版)
之前写过一篇关于springboot 与 mybatis整合的博文,使用了一段时间spring-data-jpa,发现那种方式真的是太爽了,mybatis的xml的映射配置总觉得有点麻烦.接口定义和映 ...
- (45). Spring Boot MyBatis连接Mysql数据库【从零开始学Spring Boot】
大家在开发的时候,会喜欢jdbcTemplate操作数据库,有喜欢JPA操作数据库的,有喜欢MyBatis操作数据库的,对于这些我个人觉得哪个使用顺手就使用哪个就好了,并没有一定要使用哪个,个人在实际 ...
- Spring Boot MyBatis 数据库集群访问实现
Spring Boot MyBatis 数据库集群访问实现 本示例主要介绍了Spring Boot程序方式实现数据库集群访问,读库轮询方式实现负载均衡.阅读本示例前,建议你有AOP编程基础.mybat ...
随机推荐
- Java web中文乱码
1.设置工程的编码方式 window-preferences-general-workspace 改成uef-8 2.设置html的编码方式 <meta http-equiv="Con ...
- vue 自定义指令的魅力
[第1103期]vue 自定义指令的魅力 点点 前端早读课 2017-11-08 前言 很多事情不能做过多的计划,因为计划赶不上变化.今日早读文章由富途@点点翻译分享. 正文从这开始- 在你初次接触一 ...
- C3的坑之inline-block
最近开始复习css一直在踩坑,今天分享一个inline-block 关于inline-block可能很多人都不熟悉,布局这方面很多人用的都是flex或者浮动,flex很强大毋庸置疑的可是关于兼容性就不 ...
- Mybayis的项目使用的Mapping文件使用总结参考(一)
作者:longgangbai 以前用过ibatis2,但是听说ibatis3有较大的性能提升,而且设计也更合理,他不兼容ibatis2.尽管ibatis3还是beta10的状态,但还是打算直接使用ib ...
- BZOJ 2124 (线段树 + hash)
题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=2124 题意:给一个1到N的排列{Ai},询问是否存在1<=p1<p2< ...
- JavaScript数组的简单介绍
㈠对象分类 ⑴内建对象 ⑵宿主对象 ⑶自定义对象 ㈡数组(Array) ⑴简单介绍 ①数组也是一个对象 ②它和我们普通对象功能类似,也是用来存储一些值的 ③不同的是普通对象是使用字符串作为属性名的 ...
- B/S大文件分片上传
需求:项目要支持大文件上传功能,经过讨论,初步将文件上传大小控制在500M内,因此自己需要在项目中进行文件上传部分的调整和配置,自己将大小都以501M来进行限制. 第一步: 前端修改 由于项目使用的是 ...
- Java 面试题 二
1.线程怎么保持同步 关于线程同步(7种方式) --如果朋友您想转载本文章请注明转载地址"http://www.cnblogs.com/XHJT/p/3897440.html"谢谢 ...
- 云栖社区 Tensorflow快餐教程
云栖社区 Tensorflow快餐教程(1) - 30行代码搞定手写识别:https://yq.aliyun.com/articles/582122云栖社区 Tensorflow快餐教程(2) - 标 ...
- 2016 ACM-ICPC NEERC F. Foreign Postcards (概率DP)
2016 ACM-ICPC NEERC F. Foreign Postcards 题意:有一串由C.W组成的字符串,每次截取长度为k(1<=k<=n且k随机)的前缀,如果该前缀首位为W,则 ...