博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot入门 (六) 数据库访问之Mybatis
阅读量:4541 次
发布时间:2019-06-08

本文共 4017 字,大约阅读时间需要 13 分钟。

本文记录学习在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包。

org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2

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

#datasourespring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=123456#mybatismybatis.mapper-locations=classpath:mybatis/*.xml

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

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

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

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

在xml文件中完成SQl,实现具体的方法,如下:

id, age, name
delete from t_user where id = #{id,jdbcType=BIGINT}
insert into t_user (id, age, name) values (#{id,jdbcType=BIGINT}, #{age,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR})
update t_user set age = #{age,jdbcType=INTEGER}, name = #{name,jdbcType=VARCHAR} where id = #{id,jdbcType=BIGINT}

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

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)@SpringBootTestpublic 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
userList = userMapper.selectAll(); } }

  

转载于:https://www.cnblogs.com/love-wzy/p/10334259.html

你可能感兴趣的文章
剑指offer(18)二叉搜索树的后续遍历
查看>>
微信小程序一笔记账开发进度四
查看>>
bzoj 1070 费用流
查看>>
201671010139 徐楠 第四周总结
查看>>
JAVA链表简单实现
查看>>
[转载]T-SQL(MSSQL)语句查询执行顺序
查看>>
SignalR 行实时通信最大连接数
查看>>
开发进度6
查看>>
php方法重载
查看>>
三次握手和四次挥手(二)
查看>>
MySQL中的索引
查看>>
Android开发之手势滑动(滑动手势监听)详解
查看>>
switch
查看>>
HTTP错误code大全
查看>>
PAT Advanced Level 1043
查看>>
Saltstack windows可视化操作(十四)
查看>>
MYSQL基本语句
查看>>
httpservlet在创建实例对象时候默认调用有参数的init方法 destroy()方法 service方法, 父类的init方法给子类实例一个config对象...
查看>>
MAC和PHY的区别 (转自http://www.cnblogs.com/feitian629/archive/2013/01/25/2876857.html)
查看>>
.net core部署到linux
查看>>