一、引入Maven依赖
<!-- mybatis 依赖包-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
二、配置Mapper接口路径
- 配置Mapper的位置通常有两种方式
- 1、在主类通过注解配置Mapper的包路径
@SpringBootApplication
@MapperScan("top.haostudy.springbootdemo.mapper")
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
- 2、直接在mapper上使用@Mapper注解
@Mapper
public interface ArticleEntityMapper {
ArticleEntity selectByAuthorId(@Param("authorId") int authorId)
}
三、配置application.yml
# 配置Mapper.xml的路径
mybatis:
mapper-locations: classpath:/mapper/*/*.xml
四、编写mapper接口和mapper.xml文件
- 在resouces下建立mapper文件夹,编写相关mapper.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">
<!-- namespace:配置Mapper接口的全路径 -->
<mapper namespace="top.haostudy.springbootdemo.mapper.ArticleEntityMapper">
<!-- 通用查询映射结果 type:配置返回对象的全路径-->
<resultMap id="BaseResultMap" type="top.haostudy.haostudyapi.model.dao.ArticleEntity">
<id column="article_id" property="articleId" />
<result column="type_id" property="typeId" />
<result column="content" property="content" />
<result column="create_time" property="createTime" />
<result column="update_time" property="updateTime" />
<result column="author_id" property="authorId" />
<result column="cover_img" property="coverImg" />
<result column="article_title" property="articleTitle" />
<result column="read_count" property="readCount" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
article_id, type_id, content, create_time, update_time, author_id, cover_img, article_title, read_count
</sql>
<select id="selectByAuthorId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"></include>
from
article_entity
where author_id = #{authorId}
</select>
</mapper>
五、Maven多模块项目特殊配置
- 1、主启动类上增加注解配置
// 如果是多模块Maven项目,需要指定Spring扫描的包路径,确保其他模块的Bean也能被扫描
@SpringBootApplication(scanBasePackages = "top.haostudy")
// 指定Mapper接口所在的包路径
@MapperScan("top.haostudy.springbootdemo.mapper")
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
2、配置application.yml
- 如果是多模块Maven项目,这里得配置成classpath*
mybatis:
mapper-locations: classpath*:/mapper/*/*.xml
@各位掘金的小伙伴,如有任何Java技术方面疑问可私聊本人(wx:haostudydaydayup),一起探讨一起进步。