SpringBoot整合Mybatis

依赖

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

纯注解版

如何告诉Spring容器,哪个接口是Mapper呢?

一般我们的都是单独创建一个mapper的packet, 闲麻烦可以选择使用@Mapper注解标记在单个mapper接口上,或者使用@MapperScan完成mapper的批量扫描

完成简单注解版的CURD

方法的名字见名知意就行,但是方法的返回值得是注解上sql对应的返回值

  • 查询@Select
@Select("select * from person where id=#{id}")
public Person getPersonById(Integer id);
  • 删除@Delete
@Delete("delete from person where id = #{id}")
public int deletePersonById(Integer id);
  • 添加@Insert
// 添加Options注解,指定主键自增长, keyProperty 指定主键是谁,效果是运行完insert语句后,id会封装进被插入的对象中
// 方便我们后续接着使用
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into person (name,password) values(#{name},#{name})")
public int insertPerson(Person person);
  • 更新@Update
@Update("update person set name=#{name} , password=#{password} where id=#{id}")
public int updatePerson(Person person);

配置文件版

点击进入MyBatis3官网

如下图所示,在Resources目录下面创建指定的配置文件

https://img2018.cnblogs.com/blog/1496926/201910/1496926-20191011184418159-1426148266.png

配置文件的内容在上面的官网上可以找到,我的如下

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>
<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
    <setting name="useGeneratedKeys" value="true"/>
</settings>
</configuration>

MyBankMapper.xml

<?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="com.changwu.mapper.MyBankMapper">
     <select id="getMyBankById" resultType="com.changwu.pojo.MyBank">
         select * from mybank where id = #{id}
     </select>
    <insert id="insertMyBank">
        insert into mybank (username, password, money) values (#{username},#{password},#{money})
    </insert>
</mapper>

通过在application.yml中添加配置告诉SpringBoot去哪里读取配置文件

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
posted @ 2019-10-11 18:46  赐我白日梦  阅读(450)  评论(1编辑  收藏  举报