SpringBoot里配置mybatis的十个注意点

本文详细介绍了如何在SpringBoot项目中整合MyBatis,包括添加依赖、创建mapper接口及XML文件、配置实体类、设置application.yml等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.添加依赖

implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.0.0'
testCompile 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test:2.0.0'

2.新建mapper接口文件, 与mapper.xml文件

3.mapper 接口文件前有@Mapper注释,以便于自动注入

4.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">

5.mapper.xml中的namespace路径要从类目录具体到mapper接口文件名,即copy reference path

6.mapper.xml中映射的实体类要有getter, setter方法,如是用lombok插件不要忘加依赖,以及在实体类前加@Data

7.mapper.xml中的id要与接口文件中的接口函数名对应,参数类型,返回值类型也要一一对应

8.mapper.xml中sql语句中的#{}中的名对应接口函数的参数名。

9.application.yml中要保证 mybatis: mapper-locations: 路径的正确,精确到mapper.xml,如以下是定位到resource -> mappers -> mapper.xml  classpath*:后没有空格, mybatis:和mapper-locations:后面有

mybatis:
  mapper-locations: classpath*:/**/mapper.xml

10.启动类前要加@MapperScan(basePackages="")定位到接口文件

后续有话再加

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值