首页 > 其他分享 >spring boot整合mybatis

spring boot整合mybatis

时间:2023-01-27 21:44:07浏览次数:63  
标签:xml mapper Mapper spring boot public mybatis id

1、pom.xml文件中引入mybatis-spring-boot-starte

mybatis仓库地址:https://github.com/mybatis

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>${druid-version}</version>
</dependency>

2、配置mybatis

  • yml文件中配置文件路径
# 配置mybatis规则
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml  #全局配置文件位置
  mapper-locations: classpath:mybatis/mapper/*.xml  #sql映射文件位置

  • 配置xxxMapper.xml文件,文件名与mapper接口名称一致
<?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.atguigu.admin.mapper.AccountMapper">
    <select id="getAcct" resultType="com.atguigu.admin.bean.Account">
        select * from  account_tbl where  id=#{id}
    </select>
</mapper>
  • mybatis进行详细配置
    注意:configuration只能在yml文件中或者mybatis-config.xml文件中。若写在yml文件中,config-location则需要删除
mybatis:
#  config-location: classpath:mybatis/mybatis-config.xml文件中,若写在
  mapper-locations: classpath:mybatis/mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true

# 可以不写全局配置文件,所有全局配置文件的配置都放在configuration配置项中即可

3、进行Mapper接口和Service的编写

  • 配置模式
    可以在主类中使用@MapperScan("com.xxx.xxx.mapper") 简化,推荐在每个mapper接口中使用@Mapper注解
@Mapper
public interface AccountMapper {

    public Account getAccount(String userId);

}
  • 注解模式
    不在需要编写CityMapper.xml文件
@Mapper
public interface CityMapper {

    @Select("select * from city where id=#{id}")
    public City getById(Long id);

    public void insert(City city);

}
  • 混合模式
    将配置模式和注解模式混合使用
@Mapper
public interface CityMapper {

    @Select("select * from city where id=#{id}")
    public City getById(Long id);

    public void insert(City city);

}
@Mapper
public interface AccountMapper {

    public Account getAccount(String userId);

}

标签:xml,mapper,Mapper,spring,boot,public,mybatis,id
From: https://www.cnblogs.com/shuimublog/p/17069392.html

相关文章