概述

  • 中文官网:http://www.mybatis.cn
  • 参考教程:https://www.w3cschool.cn/mybatis
  • MyBatis Plus:http://mp.baomidou.com/#/quick-start
  • 主要步骤:添加配置、生成MyBatis模板、编写服务接口、配置打包资源、编译运行测试
原理概述
程序连接数据库,反向生成程序模板。所以,要提前准备好数据库以及连接数据库的代码。
 
 
添加依赖
mybatis-spring-boot-starter,最新的版本到几就填写几,2020-05-02的版本如下:
 
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

数据源配置

适用于Mysql5.7及以下版本,mysql8.0要使用另外的配置
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.177.67:3316/dbmng?useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8
username: automng
password: Automng_123

mysql8.0连接配置,不使用SSL,同时指定时区

server:
  port: 9100
spring:
  datasource:
    #com.mysql.jdbc.Driver
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/dbmng?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
    username: automng
    password: Automng_123

mybatis架构

定义interface,xml映射关系,然后通过配置类建立他们之间的实现。

mybatis在项目中的位置,提供JDBC底层服务,业务调用mybatis方法,然后对外提供服务

创建一个Java实体类

创建创建一个XML配置文件,通过XML配置文件关联实体类属性与数据库字段

定义一个实体类对应的接口

配置mybatis,将实体类接口转化为实现类

配置一套业务接口与实现类,通过spring注解注入mybatis实现类

定义一套控制类,通过spring注解注入业务接口,对外提供服务

 添加配置类
添加MyBatis配置类,dao/model/xml等扫描,同时从spring bean 容器加载数据源
进而建立model与mapper映射文件的联系,再通过接口对外提供数据库服务
MapperScan注解将对应的接口转化为实现类
package cn.itoracle.dbmng.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver; /**
* MyBais配置类
* @author tan
* @version May 2, 2020 6:11:22 PM
*/
@Configuration
@MapperScan("cn.itoracle.dbmng.**.dao") // 扫描DAO
public class MyBatisConfig { @Autowired
private DataSource dataSource; @Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setTypeAliasesPackage("cn.itoracle.dbmng.**.model"); // 扫描Model PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sessionFactory.setMapperLocations(resolver.getResources("classpath*:**/sqlmap/*.xml")); // 扫描映射文件 return sessionFactory.getObject();
}
}
 dao接口
 
package cn.itoracle.dbmng.dao;

import java.util.List;

import cn.itoracle.dbmng.model.SysUser;

public interface SysUserMapper {
int deleteByPrimaryKey(Long id); int insert(SysUser record); int insertSelective(SysUser record); SysUser selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(SysUser record); int updateByPrimaryKey(SysUser record); /**
* 查询全部
* @return
*/
List<SysUser> findAll();
}

model类

package cn.itoracle.dbmng.model;

import java.util.Date;

public class SysUser {
private Long id; private String name; private String nickName; private String avatar; private String password; private String salt; private String email; private String mobile; private Byte status; private Long deptId; private String createBy; private Date createTime; private String lastUpdateBy; private Date lastUpdateTime; private Byte delFlag; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name == null ? null : name.trim();
} public String getNickName() {
return nickName;
} public void setNickName(String nickName) {
this.nickName = nickName == null ? null : nickName.trim();
} public String getAvatar() {
return avatar;
} public void setAvatar(String avatar) {
this.avatar = avatar == null ? null : avatar.trim();
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password == null ? null : password.trim();
} public String getSalt() {
return salt;
} public void setSalt(String salt) {
this.salt = salt == null ? null : salt.trim();
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email == null ? null : email.trim();
} public String getMobile() {
return mobile;
} public void setMobile(String mobile) {
this.mobile = mobile == null ? null : mobile.trim();
} public Byte getStatus() {
return status;
} public void setStatus(Byte status) {
this.status = status;
} public Long getDeptId() {
return deptId;
} public void setDeptId(Long deptId) {
this.deptId = deptId;
} public String getCreateBy() {
return createBy;
} public void setCreateBy(String createBy) {
this.createBy = createBy == null ? null : createBy.trim();
} public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
} public String getLastUpdateBy() {
return lastUpdateBy;
} public void setLastUpdateBy(String lastUpdateBy) {
this.lastUpdateBy = lastUpdateBy == null ? null : lastUpdateBy.trim();
} public Date getLastUpdateTime() {
return lastUpdateTime;
} public void setLastUpdateTime(Date lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
} public Byte getDelFlag() {
return delFlag;
} public void setDelFlag(Byte delFlag) {
this.delFlag = delFlag;
}
}

mapper映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://www.mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.itoracle.dbmng.dao.SysUserMapper">
<resultMap id="BaseResultMap" type="cn.itoracle.dbmng.model.SysUser">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="nick_name" jdbcType="VARCHAR" property="nickName" />
<result column="avatar" jdbcType="VARCHAR" property="avatar" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="salt" jdbcType="VARCHAR" property="salt" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="mobile" jdbcType="VARCHAR" property="mobile" />
<result column="status" jdbcType="TINYINT" property="status" />
<result column="dept_id" jdbcType="BIGINT" property="deptId" />
<result column="create_by" jdbcType="VARCHAR" property="createBy" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
<result column="last_update_by" jdbcType="VARCHAR" property="lastUpdateBy" />
<result column="last_update_time" jdbcType="TIMESTAMP" property="lastUpdateTime" />
<result column="del_flag" jdbcType="TINYINT" property="delFlag" />
</resultMap>
<sql id="Base_Column_List">
id, name, nick_name, avatar, password, salt, email, mobile, status, dept_id, create_by,
create_time, last_update_by, last_update_time, del_flag
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from sys_user
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from sys_user
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="cn.itoracle.dbmng.model.SysUser">
insert into sys_user (id, name, nick_name,
avatar, password, salt,
email, mobile, status,
dept_id, create_by, create_time,
last_update_by, last_update_time, del_flag
)
values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{nickName,jdbcType=VARCHAR},
#{avatar,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{salt,jdbcType=VARCHAR},
#{email,jdbcType=VARCHAR}, #{mobile,jdbcType=VARCHAR}, #{status,jdbcType=TINYINT},
#{deptId,jdbcType=BIGINT}, #{createBy,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP},
#{lastUpdateBy,jdbcType=VARCHAR}, #{lastUpdateTime,jdbcType=TIMESTAMP}, #{delFlag,jdbcType=TINYINT}
)
</insert>
<insert id="insertSelective" parameterType="cn.itoracle.dbmng.model.SysUser">
insert into sys_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="nickName != null">
nick_name,
</if>
<if test="avatar != null">
avatar,
</if>
<if test="password != null">
password,
</if>
<if test="salt != null">
salt,
</if>
<if test="email != null">
email,
</if>
<if test="mobile != null">
mobile,
</if>
<if test="status != null">
status,
</if>
<if test="deptId != null">
dept_id,
</if>
<if test="createBy != null">
create_by,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="lastUpdateBy != null">
last_update_by,
</if>
<if test="lastUpdateTime != null">
last_update_time,
</if>
<if test="delFlag != null">
del_flag,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=BIGINT},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="nickName != null">
#{nickName,jdbcType=VARCHAR},
</if>
<if test="avatar != null">
#{avatar,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="salt != null">
#{salt,jdbcType=VARCHAR},
</if>
<if test="email != null">
#{email,jdbcType=VARCHAR},
</if>
<if test="mobile != null">
#{mobile,jdbcType=VARCHAR},
</if>
<if test="status != null">
#{status,jdbcType=TINYINT},
</if>
<if test="deptId != null">
#{deptId,jdbcType=BIGINT},
</if>
<if test="createBy != null">
#{createBy,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
#{createTime,jdbcType=TIMESTAMP},
</if>
<if test="lastUpdateBy != null">
#{lastUpdateBy,jdbcType=VARCHAR},
</if>
<if test="lastUpdateTime != null">
#{lastUpdateTime,jdbcType=TIMESTAMP},
</if>
<if test="delFlag != null">
#{delFlag,jdbcType=TINYINT},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="cn.itoracle.dbmng.model.SysUser">
update sys_user
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="nickName != null">
nick_name = #{nickName,jdbcType=VARCHAR},
</if>
<if test="avatar != null">
avatar = #{avatar,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="salt != null">
salt = #{salt,jdbcType=VARCHAR},
</if>
<if test="email != null">
email = #{email,jdbcType=VARCHAR},
</if>
<if test="mobile != null">
mobile = #{mobile,jdbcType=VARCHAR},
</if>
<if test="status != null">
status = #{status,jdbcType=TINYINT},
</if>
<if test="deptId != null">
dept_id = #{deptId,jdbcType=BIGINT},
</if>
<if test="createBy != null">
create_by = #{createBy,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
create_time = #{createTime,jdbcType=TIMESTAMP},
</if>
<if test="lastUpdateBy != null">
last_update_by = #{lastUpdateBy,jdbcType=VARCHAR},
</if>
<if test="lastUpdateTime != null">
last_update_time = #{lastUpdateTime,jdbcType=TIMESTAMP},
</if>
<if test="delFlag != null">
del_flag = #{delFlag,jdbcType=TINYINT},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="cn.itoracle.dbmng.model.SysUser">
update sys_user
set name = #{name,jdbcType=VARCHAR},
nick_name = #{nickName,jdbcType=VARCHAR},
avatar = #{avatar,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
salt = #{salt,jdbcType=VARCHAR},
email = #{email,jdbcType=VARCHAR},
mobile = #{mobile,jdbcType=VARCHAR},
status = #{status,jdbcType=TINYINT},
dept_id = #{deptId,jdbcType=BIGINT},
create_by = #{createBy,jdbcType=VARCHAR},
create_time = #{createTime,jdbcType=TIMESTAMP},
last_update_by = #{lastUpdateBy,jdbcType=VARCHAR},
last_update_time = #{lastUpdateTime,jdbcType=TIMESTAMP},
del_flag = #{delFlag,jdbcType=TINYINT}
where id = #{id,jdbcType=BIGINT}
</update>
<select id="findAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from sys_user
</select>
</mapper>
 
 
打包时带上映射文件
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<!-- 打包时拷贝MyBatis的映射文件 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/sqlmap/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
 
 
 

遇到问题

error while downloading 'http://mybatis.org/dtd/mybatis-3-mapper.dtd' to
"http://mybatis.org/dt --> "http://www.mybatis.org/
 
 
 
 
 
 
 
 

spring boot集成mybatis框架的更多相关文章

  1. Spring Boot集成MyBatis开发Web项目

    1.Maven构建Spring Boot 创建Maven Web工程,引入spring-boot-starter-parent依赖 <project xmlns="http://mav ...

  2. 详解Spring Boot集成MyBatis的开发流程

    MyBatis是支持定制化SQL.存储过程以及高级映射的优秀的持久层框架,避免了几乎所有的JDBC代码和手动设置参数以及获取结果集. spring Boot是能支持快速创建Spring应用的Java框 ...

  3. spring boot集成mybatis(1)

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  4. spring boot集成MyBatis 通用Mapper 使用总结

    spring boot集成MyBatis 通用Mapper 使用总结 2019年 参考资料: Spring boot集成 MyBatis 通用Mapper SpringBoot框架之通用mapper插 ...

  5. spring boot集成mybatis只剩两个sql 并提示 Cannot obtain primary key information from the database, generated objects may be incomplete

    前言 spring boot集成mybatis时只生成两个sql, 搞了一个早上,终于找到原因了 找了很多办法都没有解决, 最后注意到生成sql的时候打印了一句话: Cannot obtain pri ...

  6. 【spring boot】14.spring boot集成mybatis,注解方式OR映射文件方式AND pagehelper分页插件【Mybatis】pagehelper分页插件分页查询无效解决方法

    spring boot集成mybatis,集成使用mybatis拖沓了好久,今天终于可以补起来了. 本篇源码中,同时使用了Spring data JPA 和 Mybatis两种方式. 在使用的过程中一 ...

  7. spring boot集成mybatis(2) - 使用pagehelper实现分页

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  8. spring boot集成mybatis(3) - mybatis generator 配置

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  9. spring boot 集成 Mybatis,JPA

    相对应MyBatis, JPA可能大家会比较陌生,它并不是一个框架,而是一组规范,其使用跟Hibernate 差不多,原理层面的东西就不多讲了,主要的是应用. Mybatis就不多说了,SSM这三个框 ...

随机推荐

  1. druid连接泄露故障分析

    1.问题的如何发生的 1.1.应用功能介绍 系统是一个双数据源双写单独的服务.(两个数据源是不同的存储,所以无法使用主从复制的模式,是一个切换存储介质的过渡态). 历史代码有个更新逻辑update x ...

  2. k8s入坑之路(3)containerd容器

    containerd概念: containerd主要是namebases与k8s docker不同 存放路径不一致 没有默认仓库 容器运行时: 2020年未kubernetes宣布不再支持docker ...

  3. spark搭建

    1.上传解压,配置环境变量 配置bin目录 2.修改配置文件 conf cp spark-env.sh.template spark-env.sh 增加配置 export SPARK_MASTER_I ...

  4. ThreadPoolExecutor里面4种拒绝策略(详细)

    ThreadPoolExecutor类实现了ExecutorService接口和Executor接口,可以设置线程池corePoolSize,最大线程池大小,AliveTime,拒绝策略等.常用构造方 ...

  5. 菜鸡的Java笔记 第二十五 wrapperClass 包装类

    wrapperClass 包装类         1.包装类的特点        2.装箱与拆箱操作        3.数据转型处理            内容        Object 类可以接收 ...

  6. Java设计模式之(五)——代理模式

    1.什么是代理模式 Provide a surrogate or placeholder for another object to control access to it. Proxy Patte ...

  7. [cf674E]Bear and Destroying Subtrees

    令$f_{i,j}$表示以$i$为根的子树中,深度小于等于$j$的概率,那么$ans_{i}=\sum_{j=1}^{dep}(f_{i,j}-f_{i,j-1})j$ 大约来估计一下$f_{i,j} ...

  8. [atARC109E]1D Reversi Builder

    归纳每一次操作后必然是两个颜色相同的连续段(即ww...bb...或bb...ww...),对操作的位置分类讨论不难证明正确性 当$c_{1}=c_{n}$,由于端点颜色不会修改,再根据该结论,可以得 ...

  9. [atARC102F]Revenge of BBuBBBlesort

    定义以$i$为中心(交换$p_{i-1}$和$p_{i+1}$)的操作为操作$i$ 结论1:若执行过操作$i$,则之后任意时刻都无法执行操作$i-1$或操作$i+1$ 当执行操作$i$后,必然有$p_ ...

  10. C#使用Thrift作为RPC框架实战(四)之TSocket

    前言 在前几个小节中我们讲了Thrift框架的基本概念以及重要的名称空间,接下来的几个小节,我们将站在实战的角度来深入讲解一些Thrift的重要类型.本小节我先要讲一下Thrift框架支持TCP通信的 ...