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));
}

运行结果如下:

相关推荐
牛奶咖啡1314 分钟前
学习设计模式《十八》——备忘录模式
学习·设计模式·备忘录模式·认识备忘录模式·备忘录模式的优缺点·何时使用备忘录模式·备忘录模式的使用示例
大龄门外汉40 分钟前
CPP学习之list使用及模拟实现
windows·学习·list
超浪的晨1 小时前
Java List 集合详解:从基础到实战,掌握 Java 列表操作全貌
java·开发语言·后端·学习·个人开发
超浪的晨1 小时前
Java Set 集合详解:从基础语法到实战应用,彻底掌握去重与唯一性集合
java·开发语言·后端·学习·个人开发
香蕉可乐荷包蛋1 小时前
Python学习之路(十三)-常用函数的使用,及优化
开发语言·python·学习
许白掰2 小时前
Linux入门篇学习——借助 U 盘或 TF 卡拷贝程序到开发板上
linux·学习·借助 u 盘拷贝程序到开发板上·借助 tf卡拷贝程序到开发板上
modelmd2 小时前
mysql not in 查询引发的bug问题记录
sql·mysql
scheduleTTe11 小时前
SQL增查
数据库·sql
iFulling13 小时前
【计算机网络】第四章:网络层(上)
学习·计算机网络
香蕉可乐荷包蛋13 小时前
AI算法之图像识别与分类
人工智能·学习·算法