Spring Boot(六)集成 MyBatis 操作 MySQL 8

## 一、简介

1.1 MyBatis介绍

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC代码和手动设置参数以及获取结果集。

1.2 MyBatis发展史

MyBatis 原本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis ,2013年11月迁移到Github。

1.3 MyBatis和Hibernate的区别

MyBatis 和 Hibernate 都是优秀的持久化框架,都支持JDBC(Java DataBase Connection)和JTA(Java Transaction API)事务处理。

MyBatis 优点

  • 更加轻量级,如果说Hibernate是全自动的框架,MyBatis就是半自动的框架;
  • 入门简单,即学即用,并且延续了很好的SQL使用经验;

Hibernate 优点

  • 开发简单、高效,不需要编写SQL就可以进行基础的数据库操作;
  • 可移植行好,大大降低了MySQL和Oracle之间切换的成本(因为使用了HQL查询,而不是直接写SQL语句);
  • 缓存机制上Hibernate也好于MyBatis;

1.4 MyBatis集成方式

Mybatis集成方式分为两种:

  • 注解版集成
  • XML版本集成

XML版本为老式的配置集成方式,重度集成XML文件,SQL语句也是全部写在XML中的;注解版版本,相对来说比较简约,不需要XML配置,只需要使用注解和代码来操作数据。

二、注解版 MyBatis 集成

开发环境

  • MySQL 8.0.12
  • Spring Boot 2.0.4
  • MyBatis Spring Boot 1.3.2(等于 MyBatis 3.4.6)
  • JDK 8
  • IDEA 2018.2

MyBatis Spring Boot 是 MyBatis 官方为了集成 Spring Boot 而推出的MyBatis版本。

2.1 添加依赖

设置pom.xml文件,添加如下配置

<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.12</version>
</dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version>
</dependency>

添加 MySQL 和 MyBatis 支持。

2.2 配置数据库连接

设置application.properties文件,添加如下配置

# MyBatis 配置
spring.datasource.url=jdbc:mysql://172.16.10.79:3306/mytestdb?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.type-aliases-package=com.hello.springboot.mapper
  • spring.datasource.url 数据库连接字符串
  • spring.datasource.username 数据库用户名
  • spring.datasource.password 数据库密码
  • spring.datasource.driver-class-name 驱动类型(注意MySQL 8.0的值是com.mysql.cj.jdbc.Driver和之前不同)
  • mybatis.type-aliases-package 配置mapper包名

Mapper文件说明

Mapper是MyBatis的核心,是SQL存储的地方,也是配置数据库映射的地方。

2.3 设置 MapperScan 包路径

直接在启动文件SpringbootApplication.java的类上配置@MapperScan,这样就可以省去,单独给每个Mapper上标识@Mapper的麻烦。

@SpringBootApplication
@MapperScan("com.hello.springboot.mapper")
public class SpringbootApplication {public static void main(String[] args) {SpringApplication.run(SpringbootApplication.class, args);}
}

2.4 添加代码

为了演示的简洁性,我们不做太多的分层处理了,我们这里就分为:实体类、Mapper接口、Controller类,使用Controller直接调用Mapper接口进行数据持久化处理。

User 类:

public class User {private Long id;private String name;private int age;private String pwd;//省去set、get方法
}

UserMapper 接口:

public interface UserMapper {@Select("select * from user")@Results({@Result(property = "name", column = "name")})List<User> getAll();@Select("select * from user where id=#{id}")User getById(Long id);@Insert({"insert into user(name,age,pwd) values(#{name},#{age},#{pwd})"})void install(User user);@Update({"update user set name=#{name} where id=#{id}"})void Update(User user);@Delete("delete from user where id=#{id}")void delete(Long id);
}

可以看出来,所有的SQL都是写在Mapper接口里面的。

Mapper里的注解说明

  • @Select 查询注解
  • @Result 结果集标识,用来对应数据库列名的,如果实体类属性和数据库属性名保持一致,可以忽略此参数
  • @Insert 插入注解
  • @Update 修改注解
  • @Delete 删除注解

Controller 控制器:

@RestController
@RequestMapping("/")
public class UserController {@Autowiredprivate UserMapper userMapper;@RequestMapping("/")public ModelAndView index() {User user = new User();user.setAge(18);user.setName("Adam");user.setPwd("123456");userMapper.install(user);ModelAndView modelAndView = new ModelAndView("/index");modelAndView.addObject("count", userMapper.getAll().size());return modelAndView;}
}

到此为止,已经完成了MyBatis项目的配置了,可以运行调试了。

注解版GitHub源码下载:https://github.com/vipstone/springboot-example/tree/master/springboot-mybatis

三、XML 版 MyBatis 集成

3.1 添加依赖

设置pom.xml文件,添加如下配置

<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.12</version>
</dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version>
</dependency>

添加 MySQL 和 MyBatis 支持。

3.2 配置数据库连接

设置application.properties文件,添加如下配置

# MyBatis 配置
spring.datasource.url=jdbc:mysql://172.16.10.79:3306/mytestdb?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.type-aliases-package=com.hello.springboot.entity
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
  • spring.datasource.url 数据库连接字符串
  • spring.datasource.username 数据库用户名
  • spring.datasource.password 数据库密码
  • spring.datasource.driver-class-name 驱动类型(注意MySQL 8.0的值是com.mysql.cj.jdbc.Driver和之前不同)
  • mybatis.type-aliases-package 实体类包路径
  • mybatis.config-locations 配置MyBatis基础属性
  • mybatis.mapper-locations 配置Mapper XML文件

3.3 设置 MapperScan 包路径

直接在启动文件SpringbootApplication.java的类上配置@MapperScan,这样就可以省去,单独给每个Mapper上标识@Mapper的麻烦。

@SpringBootApplication
@MapperScan("com.hello.springboot.mapper")
public class SpringbootApplication {public static void main(String[] args) {SpringApplication.run(SpringbootApplication.class, args);}
}

3.4 配置XML文件

本示例设置两个xml文件,在resource/mybatis下的mybatis-config.xml(配置MyBatis基础属性)和在resource/mybatis/mapper下的UserMapper.xml(用户和数据交互的SQL语句)。

mybatis-config.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"><configuration><typeAliases><typeAlias alias="Integer" type="java.lang.Integer"/><typeAlias alias="Long" type="java.lang.Long"/><typeAlias alias="HashMap" type="java.util.HashMap"/><typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap"/><typeAlias alias="ArrayList" type="java.util.ArrayList"/><typeAlias alias="LinkedList" type="java.util.LinkedList"/></typeAliases>
</configuration>

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace是命名空间,是mapper接口的全路径-->
<mapper namespace="com.hello.springboot.mapper.UserMapper"><!--resultMap – 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象--><resultMap id="userResultMap" type="com.hello.springboot.entity.User"><id property="name" column="username"></id></resultMap><!--sql – 可被其他语句引用的可重用语句块--><sql id="colums">id,username,age,pwd</sql><select id="findAll" resultMap="userResultMap">select<include refid="colums" />from  user</select><select id="findById" resultMap="userResultMap">select<include refid="colums" />from  userwhere  id=#{id}</select><insert id="insert" parameterType="com.hello.springboot.entity.User" >INSERT INTOuser(username,age,pwd)VALUES(#{name}, #{age}, #{pwd})</insert><update id="update" parameterType="com.hello.springboot.entity.User" >UPDATEusersSET<if test="username != null">username = #{username},</if><if test="pwd != null">pwd = #{pwd},</if>username = #{username}WHEREid = #{id}</update><delete id="delete" parameterType="java.lang.Long" >DELETE FROMuserWHEREid =#{id}</delete></mapper>

SQL 映射文件有很少的几个顶级元素(按照它们应该被定义的顺序):

  • cache – 给定命名空间的缓存配置。
  • cache-ref – 其他命名空间缓存配置的引用。
  • resultMap – 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象。
  • parameterMap – 已废弃!老式风格的参数映射。内联参数是首选,这个元素可能在将来被移除,这里不会记录。
  • sql – 可被其他语句引用的可重用语句块。
  • insert – 映射插入语句
  • update – 映射更新语句
  • delete – 映射删除语句
  • select – 映射查询语句

注意: MyBatis中 config 和 mapper 的 XML 头文件是不一样的。

config 头文件

<?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">

mapper 头文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

Mapper XML 更多配置:http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html

3.5 添加代码

为了演示的便捷性,我们添加3个类用于功能的展示,分别是实体类User.java、mapper接口UserMapper.java和控制器类UserController.java,使用控制器类直接调用UserMapper的方法,进行数据存储和查询。

User.java

package com.hello.springboot.entity;
public class User {private Long id;private String name;private int age;private String pwd;//省略set/get方法
}

UserMapper.java

package com.hello.springboot.mapper;
import com.hello.springboot.entity.User;
import java.util.List;
public interface UserMapper {List<User> findAll();User findById(Long id);void insert(User user);void update(User user);void delete(Long id);
}

注意: Mapper里的方法名必须和Mapper XML里的一致,不然会找不到执行的SQL。

UserController.java

@RestController
@RequestMapping("/")
public class UserController {@Resourceprivate UserMapper userMapper;@RequestMapping("/")public ModelAndView index() {User user = new User();user.setAge(18);user.setName("Adam");user.setPwd("123456");userMapper.insert(user);ModelAndView modelAndView = new ModelAndView("/index");modelAndView.addObject("count", userMapper.findAll().size());return modelAndView;}}

到此为止,已经完成了MyBatis项目的配置了,可以运行调试了。

XML版GitHub源码下载:https://github.com/vipstone/springboot-example/tree/master/springboot-mybatis-xml

四、总结

到目前为止我们已经掌握了MyBatis的两种集成方式,注解集成和XML集成,注解版更符合程序员的代码书写习惯,适用于简单快速查询;XML版可以灵活的动态调整SQL,更适合大型项目开发,具体的选择还要看开发场景以及个人喜好了。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/546872.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

bugku web基础$_POST

意思是通过post传入一个参数what&#xff0c;如果what的值等于flag&#xff0c;即打印出flag 这个我们有好几种办法&#xff1a; 第一种方法&#xff1a; 用FireFox的HackBar插件&#xff0c;传入参数whatflag run一下&#xff0c;爆出了flag 第二种方法&#xff1a; 写个…

Windows MinGW cmake 安装编译Opencv 3.4.3 C++开发环境

win10 _64位系统 VSCode&#xff1a;官网地址 Opencv&#xff1a;3.4.5 Cmake&#xff1a;3.9.0 MinGw&#xff1a;MinGW-W64 GCC-8.1.0&#xff08;x86_64-posix-seh&#xff09; MinGW配置&#xff1a; MinGW可以在线安装&#xff0c;也可以直接下载文件后离线解压。 …

Spring Boot (七)MyBatis代码自动生成和辅助插件

一、简介 1.1 MyBatis Generator介绍 MyBatis Generator 是MyBatis 官方出品的一款&#xff0c;用来自动生成MyBatis的 mapper、dao、entity 的框架&#xff0c;让我们省去规律性最强的一部分最基础的代码编写。 1.2 MyBatis Generator使用 MyBatis Generator的使用方式有4…

Android 性能优化提示

原文 http://developer.android.com/guide/practices/design/performance.html 性能优化 Android应用程序运行的移动设备受限于其运算能力&#xff0c;存储空间&#xff0c;及电池续航。由此&#xff0c;它必须是高效的。电池续航可能是一个促使你优化程序的原因&#xff0c;即…

Linux新安装后设置root密码

linux在安装过程中未设置root密码 导致在使用中无法su 解决方法是设置root密码&#xff1a; 输入&#xff1a; sudo passwd root [sudo] password for you: —> 输入你的密码&#xff08;你现在这个用户的密码&#xff09; Enter new UNIX password: —> 设置root …

全志A20 刷入Ubuntu/Debian Linux固件 亲测能用

测试盒子&#xff1a;小美盒子&#xff08;好像是杂牌的&#xff09; 有疑问交流可以加微信&#xff1a;1755337994 PCB板号&#xff1a;RM-MPEG-107G VER1.0 20140422 用PhoenixUSBPro刷入就行&#xff0c;要刷500多秒&#xff0c;5124G版本的配置刷完Debian系统里面看还剩1…

Spring Boot (八)MyBatis + Docker + MongoDB 4.x

一、MongoDB简介 1.1 MongoDB介绍 MongoDB是一个强大、灵活&#xff0c;且易于扩展的通用型数据库。MongoDB是C编写的文档型数据库&#xff0c;有着丰富的关系型数据库的功能&#xff0c;并在4.0之后添加了事务支持。 随着存储数据量不断的增加&#xff0c;开发者面临一个困…

外键为','(逗号)拼接ID,连接查询外键表ID

select distinct pipeIdsubstring(a.PipeIn,b.number,charindex(,,a.PipeIn,,b.number)-b.number) from B_PipeSet_Info a join master..spt_values b on b.typeP where charindex(,,,a.PipeIn,b.number)b.number 转载于:https://www.cnblogs.com/mahatmasmile/p/3582136.html…

树莓派3B+安装Android 10系统

Android Things 作为 Google 旗下的一款操作系统 (OS)&#xff0c;能够帮助开发者规模化开发和维护物联网设备。同时推出的 Android Things 控制台 (Android Things Console) 更是将简化产品开发推向极致&#xff0c;帮助开发者定期获取 Google 最新稳定性修复包以及安全升级包…

Ubuntu下安装配置VIM/GVIM(GUI-Vim)

安装命令&#xff1a; sudo apt-get install vim sudo apt-get install vim-gtk 配置&#xff1a; 打开.vimrc文件 vim ~/.vimrc在当前用户的./vimrc文件中添加如下代码&#xff0c;保存 set ai set smarttab set tabstop4 set shiftwidth4 set expandtab set nu set guif…

Spring Boot(九)Swagger2自动生成接口文档和Mock模拟数据

一、简介 在当下这个前后端分离的技术趋势下&#xff0c;前端工程师过度依赖后端工程师的接口和数据&#xff0c;给开发带来了两大问题&#xff1a; 问题一、后端接口查看难&#xff1a;要怎么调用&#xff1f;参数怎么传递&#xff1f;有几个参数&#xff1f;参数都代表什么含…

viewDidLoad等相关函数调用

viewDidLoad 此方法只有当view从nib文件初始化的时候才被调用。viewDidLoad用于初始化&#xff0c;加载时用到的。 loadView 此方法在控制器的view为nil的时候被调用。虽然经常说loadView是使用代码生成视图的时候&#xff0c;当视图第一次载入的时候调用的方法。用于使用&…

下一站,上岸@24考研er

时间过的好快&#xff0c; 考研倒计时①天 去年这个时候&#xff0c; 我应该也是充满未知地进入即将来到的考研初试 去年&#xff0c;这个时候&#xff0c;疫情&#x1f637;刚刚放开 许多人都&#x1f411;&#xff0c;发烧&#xff0c;可幸的是我受影响不大 &#x1f3…

ubuntu20.10创建QT应用程序快捷方式 Terminal中输入命令直接打开QtCreator

在Terminal中直接输入命令就能打开QtCreator&#xff0c; i.e. ~$ qtcreator就可以打开Qt Creator了。 想完成这个功能的原因是&#xff0c;一般在Linux下打命令比较方便&#xff0c;而师兄给下来的这个环境(已经打包成虚拟机&#xff0c;配置好了开发环境)&#xff0c;需要自…

NVIDIA Jetson Nano B01 安装Ubuntu 18.04.3 LTS

几乎完美安装&#xff01; NVIDIA Jetson Nano B01 Ubuntu 18.04.3 LTS 的 ROS 安装和菜鸟的踩坑记录 NVIDIA Jetson Nano B01技术规格Ubuntu 定制系统的安装 烧录时的踩坑记录 SD卡格式SD卡安全信息烧录过程中的注意事项开始安装Ubuntu进入Ubuntu系统之后的一通折腾SSH的配置…

Spring Boot(十)Logback和Log4j2集成与日志发展史

一、简介 Java知名的日志有很多&#xff0c;比如&#xff1a;JUL、Log4j、JCL、SLF4J、Logback、Log4j2&#xff0c;那么这些日志框架之间有着怎样的关系&#xff1f;诞生的原因又是解决什么问题&#xff1f;下面一起来看。 1.1 JUL Java有自己的日志框架JUL&#xff08;Java…

Python禁止最大化按钮和禁止拉伸窗口大小

# 禁止最大化按钮&#xff08;只显示最小化按钮和关闭按钮&#xff09;myPyMainForm.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)# 禁止拉伸窗口大小myPyMainForm.setFixedSize(myPyMainForm.width(), myPyMainForm.height())

Zabbix配置模板监控指定服务器主机

一、Zabbix监控指定服务器 第一里程&#xff1a;在指定服务器上安装zabbix客户端&#xff0c;即zabbix-agent 访问清华镜像站&#xff0c;找到zabbix-agent镜像 第一步 第二步 第三步 第四步 第五步 第六步 第七步 第八步&#xff1a;鼠标点击右键选择复…

Spring Boot(十一)Redis集成从Docker安装到分布式Session共享

一、简介 Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库&#xff0c;并提供多种语言的API&#xff0c;Redis也是技术领域使用最为广泛的存储中间件&#xff0c;它是「Remote Dictionary Service」首字母缩写&#xff0c;也就…

统计在从1到n的正整数中1出现的次数

问题&#xff1a; 给定一个十进制正整数N&#xff0c;写下从1开始&#xff0c;到N的所有整数&#xff0c;然后数一下其中出现的所有“1”的个数。 例如&#xff1a;N 2&#xff0c;写下1&#xff0c;2。这样只出现了1个“1”。 N 12&#xff0c;我们会写下1, 2, 3, 4, 5, 6, 7,…