​  刚毕业的第一份工作是 java 开发,项目中需要用到 mybatis,特此记录学习过程,这只是一个简单 demo,mybatis 用法很多不可能全部写出来,有更复杂的需求建议查看 mybatis 的官方中文文档,点击跳转。下面时项目环境/版本。

  • 开发工具:IDEA
  • jdk 版本:1.8
  • springboot 版本:2.03

其他依赖版本见下面 pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId>
<artifactId>mybatis-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>mybatis-test</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--mybatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--alibaba连接池依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<!--分页依赖-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

1.创建项目

​ 使用 idea 中的 spring initializr 生成 maven 项目,项目命令为 mybatis-test,选择 web,mysql,mybatis 依赖,即可成功。(详细过程不赘述,如有需要学习 springboot 创建过程,可参考这篇文章

​ 然后依照上面的 pom 文件,补齐缺少的依赖。接着创建包 entity,service 和 mybatis 映射文件夹 mapper,创建。为了方便配置将 application.properties 改成 application.yml。由于我们时 REST 接口,故不需要 static 和 templates 目录。修改完毕后的项目结构如下:

  修改启动类,增加@MapperScan("com.example.mybatistest.dao"),以自动扫描 dao 目录,避免每个 dao 都手动加@Mapper注解。代码如下:

@SpringBootApplication
@MapperScan("com.example.mybatistest.dao")
public class MybatisTestApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisTestApplication.class, args);
}
}

修改 application.yml,配置项目,代码如下:

mybatis:
#对应实体类路径
type-aliases-package: com.example.mybatistest.entity
#对应mapper映射文件路径
mapper-locations: classpath:mapper/*.xml #pagehelper物理分页配置
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count=countSql
returnPageInfo: check server:
port: 8081 spring:
datasource:
name: mysqlTest
type: com.alibaba.druid.pool.DruidDataSource
#druid连接池相关配置
druid:
#监控拦截统计的filters
filters: stat
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true
username: root
password: 123456
#配置初始化大小,最小,最大
initial-size: 1
min-idle: 1
max-active: 20
#获取连接等待超时时间
max-wait: 6000
#间隔多久检测一次需要关闭的空闲连接
time-between-eviction-runs-millis: 60000
#一个连接在池中的最小生存时间
min-evictable-idle-time-millis: 300000
#打开PSCache,并指定每个连接上PSCache的大小。oracle设置为true,mysql设置为false。分库分表设置较多推荐设置
pool-prepared-statements: false
max-pool-prepared-statement-per-connection-size: 20
http:
encoding:
charset: utf-8
enabled: true

2.编写代码

​ 首先创建数据表,sql 语句如下:

CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`age` tinyint(4) NOT NULL DEFAULT '0',
`password` varchar(255) NOT NULL DEFAULT '123456',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

​ 然后在 entity 包中创建实体类 User.java

public class User {
private int id;
private String name;
private int age;
private String password; public User(int id, String name, int age, String password) {
this.id = id;
this.name = name;
this.age = age;
this.password = password;
}
public User(){}
//getter setter自行添加
}

​ 在 dao 包下创建 UserDao.java

public interface UserDao {
//插入用户
int insert(User user);
//根据id查询
User selectById(String id);
//查询所有
List<User> selectAll();
}

​ 在 mapper 文件夹下创建 UserMapper.xml,具体的 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.example.mybatistest.dao.UserDao">
<sql id="BASE_TABLE">
user
</sql>
<sql id="BASE_COLUMN">
id,name,age,password
</sql> <insert id="insert" parameterType="com.example.mybatistest.entity.User" useGeneratedKeys="true" keyProperty="id">
INSERT INTO <include refid="BASE_TABLE"/>
<trim prefix="(" suffix=")" suffixOverrides=",">
name,password,
<if test="age!=null">
age
</if>
</trim>
<trim prefix=" VALUE(" suffix=")" suffixOverrides=",">
#{name,jdbcType=VARCHAR},#{password},
<if test="age!=null">
#{age}
</if>
</trim>
</insert> <select id="selectById" resultType="com.example.mybatistest.entity.User">
select
<include refid="BASE_COLUMN"/>
from
<include refid="BASE_TABLE"/>
where id=#{id}
</select> <select id="selectAll" resultType="com.example.mybatistest.entity.User">
select
<include refid="BASE_COLUMN"/>
from
<include refid="BASE_TABLE"/>
</select>
</mapper>

​ 至此使用 mybatis 的代码编写完了,之后要用时调用 dao 接口中的方法即可。

3.测试

​ 我们通过编写 service,controller 然后使用 postman 进行测试。

​ 首先编写 UserService.java,代码如下:

@Component
public class UserService { @Autowired
private UserDao userDao; public User getByUserId(String id){
return userDao.selectById(id);
}
//获取全部用户
public List<User> getAll(){
return userDao.selectAll();
}
//测试分页
public PageInfo<User> getAll(int pageNum,int pageSize){
PageHelper.startPage(pageNum,pageSize);
List<User> users = userDao.selectAll();
System.out.println(users.size());
PageInfo<User> result = new PageInfo<>(users);
return result;
} public int insert(User user){
return userDao.insert(user);
} }

​ 编写 UserController.java

@RestController
public class UserController { @Autowired
private UserService userService; @GetMapping("/user/{userId}")
public User getUser(@PathVariable String userId){
return userService.getByUserId(userId);
} @GetMapping("/user")
public List<User> getAll(){
return userService.getAll();
} @GetMapping("/user/page/{pageNum}")
public Object getPage(@PathVariable int pageNum,
@RequestParam(name = "pageSize",required = false,defaultValue = "10") int pageSize){
return userService.getAll(pageNum,pageSize);
} @PostMapping("/user")
public Object addOne(User user){
userService.insert(user);
return user;
}
}

​ 启动项目,通过 postman 进行请求测试,测试结果如下:

  • 插入数据:

  • 查询数据

  • 分页查询

4.注解编写 sql

​ 上面使用的是 xml 方式编写 sql 代码,其实 mybatis 也支持在注解中编写 sql,这样可以避免编写复杂的 xml 查询文件,但同时也将 sql 语句耦合到了代码中,也不易实现复杂查询,因此多用于简单 sql 语句的编写。

​ 要使用注解首先将 applicaton.yml 配置文件中的mapper-locations: classpath:mapper/*.xml注释掉。然后在 UserDao.java 中加入 sql 注解,代码如下:

public interface UserDao {
//插入用户
@Insert("insert into user(name,age,password) value(#{name},#{age},#{password})")
@Options(useGeneratedKeys=true,keyColumn="id",keyProperty="id")
int insert(User user);
//根据id查询
@Select("select * from user where id=#{id}")
User selectById(String id);
//查询所有
@Select("select * from user")
List<User> selectAll();
}

然后重新启动项目测试,测试结果跟上面完全一样。

本文原创发布于:https://www.tapme.top/blog/detail/2018-09-01-10-38

源码地址:https://github.com/FleyX/demo-project/tree/master/mybatis-test.

springboot使用Mybatis(xml和注解)全解析的更多相关文章

  1. SpringBoot整合Mybatis【非注解版】

    接上文:SpringBoot整合Mybatis[注解版] 一.项目创建 新建一个工程 ​ 选择Spring Initializr,配置JDK版本 ​ 输入项目名 ​ 选择构建web项目所需的state ...

  2. @Bean 注解全解析

    目录 @Bean 基础声明 @Bean 基本构成及其使用 @Bean 注解与其他注解产生的火花 @Profile 注解 @Scope 注解 @Lazy 注解 @DependsOn 注解 @Primar ...

  3. SpringBoot整合Logback日志框架配置全解析

    目录 本篇要点 一.Logback日志框架介绍 二.SpringBoot与Logback 1.默认日志格式 2.控制台输出 3.文件输出 4.日志级别 5.日志组 6.自定义log配置 三.logba ...

  4. SpringBoot集成Mybatis(0配置注解版)

    Mybatis初期使用比较麻烦,需要各种配置文件.实体类.dao层映射关联.还有一大推其它配置.当然Mybatis也发现了这种弊端,初期开发了generator可以根据表结构自动生成实体类.配置文件和 ...

  5. SpringBoot的外部化配置最全解析!

    目录 SpringBoot中的配置解析[Externalized Configuration] 本篇要点 一.SpringBoot官方文档对于外部化配置的介绍及作用顺序 二.各种外部化配置举例 1.随 ...

  6. SpringBoot整合MyBatis(XML)

    (1).添加依赖 <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId> ...

  7. spring-boot整合Mybatis案例(注解方式)

    1.运行环境 开发工具:intellij idea JDK版本:1.8 项目管理工具:Maven 4.0.0 2.GITHUB地址 https://github.com/nbfujx/springBo ...

  8. SpringBoot整合定时任务----Scheduled注解实现(一个注解全解决)

    一.使用场景 定时任务在开发中还是比较常见的,比如:定时发送邮件,定时发送信息,定时更新资源,定时更新数据等等... 二.准备工作 在Spring Boot程序中不需要引入其他Maven依赖 (因为s ...

  9. mybatis开发,你用 xml 还是注解?我 pick ...

    最近在看公司项目时发现有的项目mybatis是基于注解开发的,而我个人的习惯是基于xml文件开发. 对于mybatis注解开发的原理理解不够,于是翻阅了部分源码,写下此文.主要介绍了mybatis开发 ...

随机推荐

  1. leetcode-21-knapsack

    322. Coin Change Write a function to compute the fewest number of coins that you need to make up tha ...

  2. oracle如何保证读一致性 第一弹

    oracle保证读一致性原理   1:undo segment的概念                   当数据库进行修改的时候,需要把保存到以前的old的数据保存到一个地方,然后进行修改,用于保存o ...

  3. LeetCode(307) Range Sum Query - Mutable

    题目 Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclus ...

  4. LeetCode(258) Add Digits

    题目 Given a non-negative integer num, repeatedly add all its digits until the result has only one dig ...

  5. STM32——PWM基本知识及配置过程

    将通用定时器分为四个部分: 1,选择时钟 2,时基电路 3,输入捕获 4,输出比较 本节定时器PWM输出主要涉及到定时器框图右下方部分,即输出比较部分 和上一讲相同,时基时钟来源于内部默认时钟 对此有 ...

  6. poj-1011 sticks(搜索题)

    George took sticks of the same length and cut them randomly until all parts became at most 50 units ...

  7. python socket相关

    套接字的工作流程(基于TCP和 UDP两个协议) TCP和UDP对比 TCP(Transmission Control Protocol)可靠的.面向连接的协议(eg:打电话).传输效率低全双工通信( ...

  8. python学习--学习时间属性的应用(time / datetime )

    #!/usr/bin/python # -*- coding:utf-8 -*- # import time # myd={1:'a',2:'b'}# for key,value in dict.it ...

  9. 【bzoj2333】[SCOI2011]棘手的操作 可并堆+STL-set

    UPD:复杂度是fake的...大家还是去写启发式合并吧. 题目描述 有N个节点,标号从1到N,这N个节点一开始相互不连通.第i个节点的初始权值为a[i],接下来有如下一些操作: U x y: 加一条 ...

  10. 【bzoj1941】[Sdoi2010]Hide and Seek KD-tree

    题目描述 小猪iPig在PKU刚上完了无聊的猪性代数课,天资聪慧的iPig被这门对他来说无比简单的课弄得非常寂寞,为了消除寂寞感,他决定和他的好朋友giPi(鸡皮)玩一个更加寂寞的游戏---捉迷藏. ...