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 小时前
【LangChain Output Parser 输出解析器】输出篇
人工智能·学习·langchain
juniperhan9 小时前
Flink 系列第24篇:Flink SQL 集成维度表指南:存储选型、参数调优与实战避坑
大数据·数据仓库·sql·flink
AI周红伟10 小时前
周红伟:DeepSeek官方教您如何部署Hermes Agent 和接入 DeepSeek-V4-Pro
人工智能·深度学习·学习·机器学习·copilot·openclaw
Chengbei1110 小时前
AI大模型网关存在SQL注入、影响版本LiteLLM 1.81.16~1.83.7(CVE-2026-42208)
数据库·人工智能·sql·安全·web安全·网络安全·系统安全
GISer_Jing10 小时前
AI原生全栈架构理论体系:从分布式范式演进到全链路工程化理论基石
前端·人工智能·学习·ai编程
babe小鑫10 小时前
零经验转行学习数据分析的价值分析
学习·数据挖掘·数据分析
zhangrelay10 小时前
三分钟云课实践速通--单片机原理与应用--Arduino--SimulIDE--
linux·单片机·嵌入式硬件·学习·ubuntu
冷小鱼11 小时前
从关系模型(SQL)基石到AI与信创时代的智能查询语言
数据库·sql
格林威11 小时前
工业视觉检测:单样本学习 vs 传统监督学习
人工智能·深度学习·数码相机·学习·计算机视觉·视觉检测·工业相机
庞轩px11 小时前
致远互联实习复盘:一条SQL替代300次循环查询,组织架构选择器从5秒降到300毫秒
java·sql·mysql·mybatis·实习经历·n+1问题·join联表查询