SpringBoot入门 (六) 数据库访问之Mybatis
本文记录学习在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的更多相关文章
- SpringBoot入门 (四) 数据库访问之JdbcTemplate
本文记录在SpringBoot中使用JdbcTemplate访问数据库. 一 JDBC回顾 最早是在上学时接触的使用JDBC访问数据库,主要有以下几个步骤: 1 加载驱动 Class.forName( ...
- SpringBoot入门 (五) 数据库访问之spring data jpa
本文记录学习使用spring data jpa访问数据库 一 什么是Spring Data JPA JPA(Java Persistence API)是Sun官方提出的Java持久化规范.它为Java ...
- step by step 之餐饮管理系统六(数据库访问模块)
距上次写的博客已经好几个月,一方面公司里面有很多的东西要学,平时的时候又要写代码,所以没有及时更新,不过现在还好,已经成型了,现在把之前的东西贴出来,先看一下现在做的几个界面吧.第一个界面是用颜色用区 ...
- SpringBoot入门之基于Druid配置Mybatis多数据源
上一篇了解了Druid进行配置连接池的监控和慢sql处理,这篇了解下使用基于基于Druid配置Mybatis多数据源.SpringBoot默认配置数据库连接信息时只需设置url等属性信息就可以了,Sp ...
- SpringBoot入门之基于XML的Mybatis
上一博客介绍了下SpringBoot基于注解引入Mybatis,今天介绍基于XML引入Mybatis.还是在上一篇demo的基础上进行修改. 一.Maven引入 这个与上一篇的一样,需要引入mybat ...
- SpringBoot入门之基于注解的Mybatis
今天学习下SpringBoot集成mybatis,集成mybatis一般有两种方式,一个是基于注解的一个是基于xml配置的.今天先了解下基于注解的mybatis集成. 一.引入依赖项 因为是mybat ...
- SpringBoot入门 (七) Redis访问操作
本文记录学习在SpringBoot中使用Redis. 一 什么是Redis Redis 是一个速度非常快的非关系数据库(Non-Relational Database),它可以存储键(Key)与 多种 ...
- springboot 入门六-多环境日志配置
在应用项目开发阶段,需要对日志进入很详细的输出便于排查问题原因,上线发布之后又只需要输出核心的日志信息的场景.springboot也提供多环境的日志配置.使用springProfile属性来标识使用那 ...
- SpringBoot入门笔记(四)、通常Mybatis项目目录结构
1.工程启动类(AppConfig.java) 2.实体类(domain) 3.数据访问层(dao) 4.数据服务层(service) 5.前端控制器(controller) 6.工具类(util) ...
随机推荐
- 单元测试工具Numega BoundsChecker
1 前言 我在本文中详细介绍了测试工具NuMega Devpartner(以下简称NuMega)的使用方法. NuMega是一个动态测试工具,主要应用于白盒测试.该工具的特点是学习简单.使用方便.功能 ...
- Accepted Technical Research Papers and Journal First Papers 【ICSE2016】
ICSE2016 Accepted Paper Accepted Technical Research Papers and Journal First Papers Co-chairs: Wille ...
- DevOps Workshop 研发运维一体化(成都站) 2016.05.08
成都的培训与广州.上海.北京一样,只是会议室比较小,比较拥挤,大家都将就了.可惜换了电脑以后,没有找到培训时的照片了,遗憾. 培训思路基没有太大变化,基本按照下面的思路进行: 第一天对软件开发的需求管 ...
- vs2017 xamarin新建单独UWP类库提示不兼容
One or more projects are incompatible with UAP,Version=v10.0 (win10-arm). One or more projects are i ...
- NetCore入门篇:(四)Net Core项目启动文件Startup
一.Startup介绍 1.Startup文件是Net Core应用程的启动程序,实现全局配置. 2.Net Core默认情况下,静态文件及Session都未启动,需要在Startup文件配置启动,否 ...
- 第五章 HashMap源码解析
5.1.对于HashMap需要掌握以下几点 Map的创建:HashMap() 往Map中添加键值对:即put(Object key, Object value)方法 获取Map中的单个对象:即get( ...
- Day 46 视图、存储过程、触发器、函数、事物、锁
一 .存储过程 create view stu_view as select * from ren 视图:是一个虚拟表,其内容由查询定义.同真实的表一样,视图包含一系列带有名称的列和行数据 视图有如下 ...
- OpenStack kolla 多 region 部署配置
region one: cat /etc/kolla/globals.yml openstack_region_name: "RegionOne" multiple_regions ...
- 通过网站统计或系统监视器查看IIS并发连接数
如果要查看IIS连接数,最简单方便的方法是通过“网站统计”来查看,“网站统计”的当前在线人数可以认为是当前IIS连接数;如果要想知道确切的当前网站IIS连接数的话,最有效的方法是通过windows自带 ...
- ubuntu 中 mongodb 数据读写权限配置
首先,我们先对mongodb 数据库的权限做一点说明: 1 默认情况下,mongodb 没有管理员账号 2 只有在 admin 数据库中才能添加管理员账号并开启权限 3 用户只能在所在的数据库中登录, ...