mybatis学习记录(三)-----关于SQL Mapper的namespace

关于SQL Mapper的namespace

视频总结笔记:

在SQL Mapper配置文件中<mapper>标签的namespace属性可以翻译为命名空间,这个命名空间主要是为了防止SQL id 冲突的。

创建CarMapper2.xml文件,代码如下:

CarMapper2.xml:

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="car2">
    <select id="selectCarAll" resultType="com.powernode.mybatis.pojo.Car">
        select
            id, car_num as carNum, brand, guide_price as guidePrice, produce_time as produceTime, car_type as carType
        from
            t_car
    </select>
</mapper>

不难看出,CarMapper.xml和CarMapper2.xml文件中都有 id="selectCarAll"

将CarMapper2.xml配置到mybatis-config.xml文件中。

mybatis-config.xml:

XML 复制代码
<mappers>
  <mapper resource="CarMapper.xml"/>
  <mapper resource="CarMapper2.xml"/>
</mappers>

编写Java代码如下:

CarMapperTest.testNamespace:

java 复制代码
@Test
public void testNamespace(){
    // 获取SqlSession对象
    SqlSession sqlSession = SqlSessionUtil.openSession();
    // 执行SQL语句
    List<Object> cars = sqlSession.selectList("selectCarAll");
    // 输出结果
    cars.forEach(car -> System.out.println(car));
}

运行结果如下:

异常信息:

sql 复制代码
org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.lang.IllegalArgumentException: 
  selectCarAll is ambiguous in Mapped Statements collection (try using the full name including the namespace, or rename one of the entries) 
  【翻译】selectCarAll在Mapped Statements集合中不明确(请尝试使用包含名称空间的全名,或重命名其中一个条目)
  【大致意思是】selectCarAll重名了,你要么在selectCarAll前添加一个名称空间,要有你改个其它名字。

ava代码修改如下:

CarMapperTest.testNamespace:

java 复制代码
@Test
public void testNamespace(){
    // 获取SqlSession对象
    SqlSession sqlSession = SqlSessionUtil.openSession();
    // 执行SQL语句
    //List<Object> cars = sqlSession.selectList("car.selectCarAll");
    List<Object> cars = sqlSession.selectList("car2.selectCarAll");
    // 输出结果
    cars.forEach(car -> System.out.println(car));
}

运行结果如下:

相关推荐
小弥儿9 小时前
GitHub今日热榜 | 2026-08-26:AI 大脑与知识管理扎堆
人工智能·学习·开源·github
荷蒲9 小时前
【小白量化Qbuddy】利用AI学习中文Python
人工智能·python·学习
中科高级技工学校10 小时前
乌鲁木齐中医康复学习经历分享
大数据·学习
JavaPub-rodert11 小时前
具身智能行业技术全景:从感知、规划、控制到 VLA 与机器人学习
学习·机器人
动力 continue12 小时前
MySQL 基础篇 · SELECT 查询大
数据库·sql·mysql·select
知识分享小能手13 小时前
概理论与数理统计学习教程,从入门到精通,在数理统计中应用R软件(22)
开发语言·学习·r语言
陈年老古董14 小时前
CentOS编译安装Python3.11完整教程
linux·笔记·学习·centos·python3.11
戈文波Geir-Wenbo Ge14 小时前
深度七步:从学习到主宰
学习
clorinda14 小时前
OpenCV实战学习记录:图像拼接与答题卡识别
人工智能·opencv·学习
red_redemption14 小时前
自由学习记录(221)
学习·renderdoc