本文记录学习在SpringBoot中使用Mybatis。

一 什么是Mybatis

  MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录(官方定义);

官方使用示例代码如下:

String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
try {
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
} finally {
session.close();
}

通过示例程序可以看到它的执行过程主要有以下几个步骤:

  1 应用程序启动时,根据配置文件生成一个SqlSessionFactory;

  2 通过SqlSessionFactory的到一个SqlSession;

  3 SqlSession内部通过Excutor执行对应的SQl;

  4 返回处理结果;

  5 释放资源;

二 SpringBoot集成Mybatis

  Mybatis使用有2中方式,一种是使用注解,即在接口定义的方法上通过注解写入要执行的SQL和要完成的数据映射;一种是使用xml配置文件即在xml文件中写相关SQL和完成表与实体的映射。本文我们使用xml文件。

  首先需要引入SpringBoot集成Mybatis的依赖jar包,这里我们只引入了Spring与Mybatis集成的包,springboot默认会自动帮我们引入其他依赖的jar包。

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>

在application.properties文件中配置数据库连接信息和指定mybatis的接口对应的xml

#datasoure
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
#mybatis
mybatis.mapper-locations=classpath:mybatis/*.xml

如上,我们的mapper xml文件放在reources目录下的mybatis文件夹下

写一个接口,定义我们要完成的功能

@Mapper
public interface UserMapper { /**
* 根据ID删除
*/
int deleteByPrimaryKey(Long id); /**
* 新增
*/
int insert(UserInfo record); /**
* 根据ID查询
*/
UserInfo selectByPrimaryKey(Long id); /**
* 修改
*/
int updateByPrimaryKey(UserInfo record); /**
* 查询所有
*/
List<UserInfo> selectAll();
}

@Mapper 该注解说名当前类是一个Mybatis的Mapper接口类,交给spring管理,令一种方式是使用注解 @MapperScan(basePackages="...") 说明basePackages及其子包下的接口都交给spring管理,我们多数情况下都会使用@MapperScan这个注解,这样我们就不用在每一个Mapper接口上写注解了。
在xml文件中完成SQl,实现具体的方法,如下:

<?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="org.allen.demo.dao.UserMapper" >
<resultMap id="BaseResultMap" type="org.allen.demo.domain.UserInfo" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="age" property="age" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
id, age, name
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
select
<include refid="Base_Column_List" />
from t_user
where id = #{id,jdbcType=BIGINT}
</select>
<select id="selectAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_user
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
delete from t_user
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="org.allen.demo.domain.UserInfo" useGeneratedKeys="true" keyProperty="id">
insert into t_user (id, age, name)
values (#{id,jdbcType=BIGINT}, #{age,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR})
</insert>
<update id="updateByPrimaryKey" parameterType="org.allen.demo.domain.UserInfo" >
update t_user
set age = #{age,jdbcType=INTEGER},
name = #{name,jdbcType=VARCHAR}
where id = #{id,jdbcType=BIGINT}
</update>
</mapper>

 从这个xml文件,我们可以看到以下几点:

1 namespace="org.allen.demo.dao.UserMapper" 通过namespace来指定将当前xml文件的SQL实现的对应的接口Mapper

2 通过 resultMap 完成实体类与数据库表字段的映射

3 xml中的SQL语句都必须写在<select> <insert> <update><delete>内部

4 每一个标识的id都必须与接口中的方法名保持一直

5 insert 中使用的 useGeneratedKeys 设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。如果设置了true,我们就可以在insert完成后直接通过当前操作的实体类获取数据库主键。

三 测试

  使用Junit做测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisApplicationTests { @Resource
private UserMapper userMapper; @Test
public void save() {
UserInfo user = new UserInfo();
user.setName("world");
user.setAge(2);
userMapper.insert(user);
System.out.println("保存后的ID:" + user.getId());
} @Test
public void delete() {
long id = 5;
userMapper.deleteByPrimaryKey(id);
} @Test
public void update() {
UserInfo user = new UserInfo();
user.setName("world");
user.setAge(5);
long id = 3;
user.setId(id);
userMapper.updateByPrimaryKey(user);
} @Test
public void selectById() {
long id = 3;
userMapper.selectByPrimaryKey(id);
} @Test
public void selectAll() {
List<UserInfo> userList = userMapper.selectAll();
} }

  

SpringBoot入门 (六) 数据库访问之Mybatis的更多相关文章

  1. SpringBoot入门 (四) 数据库访问之JdbcTemplate

    本文记录在SpringBoot中使用JdbcTemplate访问数据库. 一 JDBC回顾 最早是在上学时接触的使用JDBC访问数据库,主要有以下几个步骤: 1 加载驱动 Class.forName( ...

  2. SpringBoot入门 (五) 数据库访问之spring data jpa

    本文记录学习使用spring data jpa访问数据库 一 什么是Spring Data JPA JPA(Java Persistence API)是Sun官方提出的Java持久化规范.它为Java ...

  3. step by step 之餐饮管理系统六(数据库访问模块)

    距上次写的博客已经好几个月,一方面公司里面有很多的东西要学,平时的时候又要写代码,所以没有及时更新,不过现在还好,已经成型了,现在把之前的东西贴出来,先看一下现在做的几个界面吧.第一个界面是用颜色用区 ...

  4. SpringBoot入门之基于Druid配置Mybatis多数据源

    上一篇了解了Druid进行配置连接池的监控和慢sql处理,这篇了解下使用基于基于Druid配置Mybatis多数据源.SpringBoot默认配置数据库连接信息时只需设置url等属性信息就可以了,Sp ...

  5. SpringBoot入门之基于XML的Mybatis

    上一博客介绍了下SpringBoot基于注解引入Mybatis,今天介绍基于XML引入Mybatis.还是在上一篇demo的基础上进行修改. 一.Maven引入 这个与上一篇的一样,需要引入mybat ...

  6. SpringBoot入门之基于注解的Mybatis

    今天学习下SpringBoot集成mybatis,集成mybatis一般有两种方式,一个是基于注解的一个是基于xml配置的.今天先了解下基于注解的mybatis集成. 一.引入依赖项 因为是mybat ...

  7. SpringBoot入门 (七) Redis访问操作

    本文记录学习在SpringBoot中使用Redis. 一 什么是Redis Redis 是一个速度非常快的非关系数据库(Non-Relational Database),它可以存储键(Key)与 多种 ...

  8. springboot 入门六-多环境日志配置

    在应用项目开发阶段,需要对日志进入很详细的输出便于排查问题原因,上线发布之后又只需要输出核心的日志信息的场景.springboot也提供多环境的日志配置.使用springProfile属性来标识使用那 ...

  9. SpringBoot入门笔记(四)、通常Mybatis项目目录结构

    1.工程启动类(AppConfig.java) 2.实体类(domain) 3.数据访问层(dao) 4.数据服务层(service) 5.前端控制器(controller) 6.工具类(util) ...

随机推荐

  1. Hibernate中OpenSessionInViewFilter(通常配置在web.xml文件中)的作用

    Spring为我们解决Hibernate的Session的关闭与开启问题. Hibernate 允许对关联对象.属性进行延迟加载,但是必须保证延迟加载的操作限于同一个 Hibernate Sessio ...

  2. 动态的把固定格式的json数据以菜单形式插入

    var root=$("#side-menu"); $(menuData).each(function(i,n){ var top1Li=$("<li>< ...

  3. windows eclipse IDE打开当前类所在文件路径

    1. 展开如下菜单: Run ---- External Tools ---- External Tools Configurations 2. 在 program 下面新建一个工具 program- ...

  4. subprocess.Popen 运行windows命令出现“句柄无效”报错的解决方法

    在框架开发中遇到 subprocess执行多了,就会好句柄无效的问题,终于找到解决方案:如下,修改subprocess中的一点代码就好,也不知道这是不是Python 的bug因为,Python27时没 ...

  5. LINQ to objects遇到的小坑

    1.C#中LINQ to Objects中延迟查询的陷阱(其他类型的LINQ也基本一致) 之前在不了解LINQ延迟查询的时候,我使用下面的这种方式,将where语句的结果直接as为List<T& ...

  6. 命名空间“Microsoft”中不存在类型或命名空间名“Reporting”(是否缺少程序集引用?)

    IDE升级到VS2017之后,出现了如题所示的报错,重新引用DLL的方法如下: 1.右键引用,选择添加引用. 2.左侧选择浏览,下面点击浏览按钮. 3.分别添加Microsoft.ReportView ...

  7. 检查网卡是否支持 SR-IOV

    [root@node1 ~]# lspci -nn | grep Eth 08:00.0 Ethernet controller [0200]: Intel Corporation I350 Giga ...

  8. python使用venv环境报Python.h : No such file or direc

    这个是因为域名 install python36的时候没有按照python36-devel ,只需要 yum install python36-devel 然后重新安装所需模块即可.

  9. umeng推送, 生产环境deviceToken失效可能原因

    1 在系统升级之后会造成app的deviceToken重置(一定). 2 在app卸载之后可能会造成app的deviceToken重置. 3 deviceToken重置使用umeng推送时会因为dev ...

  10. C/C++ 语言 Hello world

    #include <stdio.h> void main() { int x,i; ; scanf("%d",&x); if(x>y) printf(&q ...