简介

MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注SQL本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、
结果集检索等jdbc繁杂的过程代码。

配置文件

MybatisConfig.xml

SSM中需要配置

数据url
数据库连接池
映射文件
事务
在SpringBoot中整合到property中了

Mapper.xml

namespace
接口绑定 和接口 就可以不用写DAO实现类,Mybatis会通过绑定自动找到要执行的sql语句。 resultMap 结果集对应到实体类的字段到属性映射

xml 方式

传统方式

xml配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-- version: $Id$ -->
<configuration>
<!-- 引用JDBC属性的配置文件 -->
<properties resource="database.properties" /> <environments default="development">
<environment id="development">
<!-- 使用JDBC的事务管理 -->
<transactionManager type="JDBC" />
<!-- POOLED :JDBC连接对象的数据源连接池的实现,不直接支持第三方数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.username}" />
<property name="password" value="${database.password}" />
</dataSource>
</environment> </environments> <!-- ORM映射文件 -->
<mappers>
<!-- 注解的方式 -->
<mapper class="com.iflytek.dao.mapper.AccountMapper" />
<!-- XML的方式 -->
<mapper resource="com/mashibing/dao/xml/AccountMapper.xml" />
<!-- 这里对于注解,还可以通过<package name="com.mashibing.dao.mapper"/> -->
</mappers>
</configuration>

Service 配置

public class AccountService {  

    public boolean insertAccount(Account account) {
boolean flag = false;
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
accountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
int result = accountMapper.insert(student);
if (result > ) {
flag = true;
}
sqlSession.commit();
} finally {
sqlSession.close();
}
return flag;
} public Student getAccountById(int id) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
AccountMapper AccountMapper = sqlSession.getMapper(AccountMapper.class);
return AccountMapper.selectByPrimaryKey(id);
} finally {
sqlSession.close();
}
} public List<Student> getAllStudents() {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper StudentMapper = sqlSession.getMapper(StudentMapper.class);
return StudentMapper.selectByExample(new StudentExample());
} finally {
sqlSession.close();
}
} public boolean updateAccount(Account account) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
boolean flag = false;
try {
AccountMapper AccountMapper = sqlSession.getMapper(AccountMapper.class);
int result = AccountMapper.updateByPrimaryKey(Account);
if (result > ) {
flag = true;
}
sqlSession.commit();
} finally {
sqlSession.close();
}
return flag; } public boolean deleteAccount(int id) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
boolean flag = false;
try {
AccountMapper AccountMapper = sqlSession.getMapper(AccountMapper.class);
int result = AccountMapper.deleteByPrimaryKey(id);
if (result > ) {
flag = true;
}
sqlSession.commit();
} finally {
sqlSession.close();
}
return flag;
} }

与SpringBoot整合

引入依赖

<?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.</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1..RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>springboot03-mybatis</artifactId>
<version>0.0.-SNAPSHOT</version>
<name>springboot03-mybatis</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

mapper

<?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.mashibing.springboot.mapper.AccountMapper"> <resultMap type="com.mashibing.springboot.mapper.Account" id="BaseResultMap"> <result column="login_name" property="loginName"/>
<result column="password" property="password"/> </resultMap> <insert id="save" parameterType="Account">
INSERT INTO account(login_name,password)
VALUES
(
#{loginName},#{password}
)
</insert> <select id="findAll" resultMap="BaseResultMap">
select * from account
</select> </mapper>

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
##数据库用户名
spring.datasource.username=root
##数据库密码
spring.datasource.password= # 用来实例化mapper接口
mybatis.type-aliases-package=com.mashibing.springboot.mapper
# 对应的sql映射
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

AccountMapper

package com.mashibing.springboot.mapper;

import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface AccountMapper { void save(Account account);
}

Account

public class Account {
private int id;
private String loginName;
private String password;
private String nickName;
private int age;
private String location;
private int banlance;
public int getId() {

显示日志

logging.level.com.mashibing.springboot.mapper=debug

注解查询

@Select("select * from account1")
List<Account> findAll();

查找mapper接口

在入口加入 MapperScan

@MapperScan("com.mashibing.springboot.mapper") public class Springboot03MybatisApplication {

每一个mapper接口上加入

@Mapper public interface AccountMapper {

Mapper 自动生成

eclipse插件 市场搜素

MyBatis Generator

图形化

https://github.com/zouzg/mybatis-generator-gui

分页查询

依赖

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.</version>
</dependency>

Service

    public Object findPage(int pageNum, int pageSize) {

        PageHelper.startPage(pageNum, pageSize);
AccountExample example = new AccountExample();
return mapper.selectByExample(example );
}

SpringBootMVC04——Mybatis的更多相关文章

  1. 【分享】标准springMVC+mybatis项目maven搭建最精简教程

    文章由来:公司有个实习同学需要做毕业设计,不会搭建环境,我就代劳了,顺便分享给刚入门的小伙伴,我是自学的JAVA,所以我懂的.... (大图直接观看显示很模糊,请在图片上点击右键然后在新窗口打开看) ...

  2. Java MyBatis 插入数据库返回主键

    最近在搞一个电商系统中由于业务需求,需要在插入一条产品信息后返回产品Id,刚开始遇到一些坑,这里做下笔记,以防今后忘记. 类似下面这段代码一样获取插入后的主键 User user = new User ...

  3. [原创]mybatis中整合ehcache缓存框架的使用

    mybatis整合ehcache缓存框架的使用 mybaits的二级缓存是mapper范围级别,除了在SqlMapConfig.xml设置二级缓存的总开关,还要在具体的mapper.xml中开启二级缓 ...

  4. 【SSM框架】Spring + Springmvc + Mybatis 基本框架搭建集成教程

    本文将讲解SSM框架的基本搭建集成,并有一个简单demo案例 说明:1.本文暂未使用maven集成,jar包需要手动导入. 2.本文为基础教程,大神切勿见笑. 3.如果对您学习有帮助,欢迎各种转载,注 ...

  5. mybatis plugins实现项目【全局】读写分离

    在之前的文章中讲述过数据库主从同步和通过注解来为部分方法切换数据源实现读写分离 注解实现读写分离: http://www.cnblogs.com/xiaochangwei/p/4961807.html ...

  6. MyBatis基础入门--知识点总结

    对原生态jdbc程序的问题总结 下面是一个传统的jdbc连接oracle数据库的标准代码: public static void main(String[] args) throws Exceptio ...

  7. Mybatis XML配置

    Mybatis常用带有禁用缓存的XML配置 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ...

  8. MyBatis源码分析(一)开篇

    源码学习的好处不用多说,Mybatis源码量少.逻辑简单,将写个系列文章来学习. SqlSession Mybatis的使用入口位于org.apache.ibatis.session包中的SqlSes ...

  9. (整理)MyBatis入门教程(一)

    本文转载: http://www.cnblogs.com/hellokitty1/p/5216025.html#3591383 本人文笔不行,根据上面博客内容引导,自己整理了一些东西 首先给大家推荐几 ...

随机推荐

  1. OpenCV学习笔记(8)——图像平滑

    使用不同的低筒滤波器对图像进行模糊 使用自定义的率弄起对图像进行卷积(2D卷积) 2D卷积 与信号一样,我们也可以对2D图像实施低通滤波,高通滤波等.LPF帮助我们去除噪声,模糊图像.而HPF帮助我们 ...

  2. Python Module_sys/random

    目录 目录 前言 软件环境 Python标准库初识 Python常用的标准库模块 dir 函数使用方法 sys操作系统功能模块 sysstdinsysstdoutsysstderr标准IOError流 ...

  3. ES6的对象属性简写

    在ES6中允许我们在设置一个对象的属性的时候不指定属性名. 不使用ES6: const name='Ming', age='18', city='Shanghai'; const student ={ ...

  4. Git使用手册/Git教程:git fetch 将远程仓库的分支及分支最新版本代码拉取到本地

    相关文章: 关于验证是否存在ssh配置以及生成SSH Key的方法可以参照文章:Git使用手册:生成SSH Key 关于SSH Key的使用和公钥在gitHub.gitLab的配置等,请参考文章:Gi ...

  5. Dojo入门:DOM操作

      作为一款功能齐全的js工具包,dojo提供了统一的DOM操作方法. dojo.byId dojo.byId 函数使您可以通过 id 属性选择一个 DOM 节点.该函数是标准 document.ge ...

  6. 【ABAP系列】SAP ABAP获取域(domain)值的方法

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[ABAP系列]SAP ABAP获取域(doma ...

  7. 主机加固之win7

    这套主机加固方案很简单,一步一步按着顺序来弄就可以,部分步骤还配有相关图片.可以先用虚拟机来做一次加固,以防弄错后不好恢复.记得弄个快照,以防万一.下次有空写个win7暴力破解~ 1. 配置管理 1. ...

  8. mysql中索引类型

    mysql索引类型normal,unique,full text的是什么? normal:表示普通索引 unique:表示唯一的,不允许重复的索引,如果该字段信息保证不会重复例如身份证号用作索引时,可 ...

  9. Junit4 简单使用

    一.环境搭建 对于习惯使用Eclipse开发平台来说,Junit早已是非常通常的插件,在Eclipse开发平台中,可以非常方便地搭建Junit测试环境. 1.在Eclipse上创建工程,任何Java工 ...

  10. 第七周作业&实验报告5

     实验四 类的继承 实验目的 理解抽象类与接口的使用: 了解包的作用,掌握包的设计方法. 实验要求 掌握使用抽象类的方法. 掌握使用系统接口的技术和创建自定义接口的方法. 了解 Java 系统包的结 ...