简介

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. 实现一个可以用 await 异步等待的 Awaiter

    总结起来,要想使一个方法可被 await 等待,必须具备以下条件: 这个方法返回一个类 A 的实例,这个类 A 必须满足后面的条件.此类 A 有一个可被访问到的 GetAwaiter 方法(扩展方法也 ...

  2. EventChannel 原生向Flutter传递数据

    目的:原生页面主动向Flutter页面传递信息 1 flutter步骤 定义EventChannel static const EventChannel eventChannel = EventCha ...

  3. SAEJ1757-1-2015(一)

    SURFACE VEHICLE STANDARD           表面车辆标准 Standard Metrology for Vehicular Displays             车载显示 ...

  4. IDEA里面maven菜单解读

  5. python读取在文件中以unicode编码方式转成中文

    row='\u4E09\u56FD\u6F14\u4E49' eval("u"+"\'"+row+"\'")

  6. InputNumber计数器

    InputNumber 计数器 仅允许输入标准的数字值,可定义范围 要使用它,只需要在el-input-number元素中使用v-model绑定变量即可,变量的初始值即为默认值. <templa ...

  7. java利用dom4j读取xml

    java连接oracle数据库的时候, 需要从特定地方读取xml文件中的sql去get结果集, xml文件放在和java文件: SqlLoaderFromXML的目录下OracleSQL, xml文件 ...

  8. nmon服务器监控工具的使用安装

    nmon是一个监控服务器性能的工具 目录 1.安装nmon 2.数据采集 1.安装nmon nmon是一种linux服务器性能监控工具,他还提供了很好的图表结果展示功能.本篇以centos6.5系统为 ...

  9. oracle数据字典视图

    数据字典的概念       还记得我们在手工建库的时候,运行的两个脚本文件.一个是catalog.sql,另一个是catproc.sql.catalog.sql是用来创建数据库的内部字典表的.catp ...

  10. centos7.5搭建svn

    1.安装svnyum install subversion 2.查看安装位置rpm -ql subversion 3.创建svn版本库目录mkdir -p /var/svn/svnrepos 4.创建 ...