Spring Boot整合Mybatis流程笔记

本文详细介绍了如何将Spring Boot与Mybatis进行整合,包括添加mybatis-spring-boot-starter依赖、配置数据库连接、创建Mapper接口及XML文件,使用@MapperScan注解扫描Mapper接口,并设置mybatis.mapper-locations属性指定XML位置。同时,讨论了@SelectKey注解实现主键回填以及解决XML文件在打包时被忽略的问题。
摘要由CSDN通过智能技术生成

依赖         

mybatis-spring-boot-starter(第三方特供)

 

1.在 application.properties 中配置数据库

 

2.0创建XxxMapper接口

@Select、@Insert、@Update、@Delete

@Results类似XML中的ResultMap映射文件

@SelectKey 注解可以实现主键回填的功能,即当数据插入成功后,插入成功的数据 id 会赋值到 user 对象的id 属性上。

@Results({

            @Result(property = "id", column = "id"),

            @Result(property = "username", column = "u"),

            @Result(property = "address", column = "a")

    })

@Select("select username as u,address as a,id as id from user where id=#{id}")

    User getUserById(Long id);

@Select("select * from user where username like concat('%',#{name},'%')")

    List<User> getUsersByName(String name);

@Insert({"insert into user(username,address) values(#{username},#{address})"})

@SelectKey(statement = "select last_insert_id()", keyProperty = "id", before = false, resultType = Integer.class)

    Integer addUser(User user);.

 

3.配置mapper扫描

  1. 每个mapper接口添加@Mapper注解
  2. 启动类添加@MapperScan(basePackages="mapper包")

2.1XML

  1. XxMaaper接口(只有方法名)
  2. 创建XxMapper.xml文件
    1. 放在resource下必须和XxMapper接口包目录相同的目录层级(才能确保打包后xml和mapper接口又处在一起)
      1. 此时在 application.properties 中告诉 mybatis 去哪里扫描 mapper   mybatis.mapper-locations=classpath:mapper/*.xml
    2. 与XxMapper接口在一起(maven在打包时会忽略掉java下的xml,所以需要在pom.xml 文件中配置文件过滤 如下:

解决xml与mapper接口一起不被maven打包方法

<build>

    <resources>

        <resource>

            <directory>src/main/java</directory>

            <includes>

                <include>**/*.xml</include>

            </includes>

        </resource>

        <resource>

            <directory>src/main/resources</directory>

        </resource>

    </resources>

</build>

在 SSM 整合中,开发者需要自己提供两个 Bean,一个SqlSessionFactoryBean ,还有一个是 MapperScannerConfigurer,在 Spring Boot 中,这两个东西虽然不用开发者自己提供了,但是并不意味着这两个 Bean 不需要了,在 org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration 类中,我们可以看到 Spring Boot 提供了这两个 Bean

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值