SQL映射文件

XxxxMapper.xml:专门用来编写SQL语句映射文件(一个对应一个),如t_user表一般会对应一个UserMapper.xml

mappernamespace属性

如果两个SQL映射文件中的sqlid重名,Mybatis无法确定执行哪个SQL语句提示sqlid集合中不明确(请尝试使⽤包含名称空间的全名或重命名其中⼀个条⽬)

mybatis-config.xml核心配置文件引入CarMapper.xmlCarMapper2.xml

<!--引入sql映射文件-->
<mappers>
    <mapper resource="CarMapper.xml"/>
    <mapper resource="CarMapper2.xml"/>
</mappers>

CarMapper.xmlCarMapper2.xml两个SQL映射文件中都有 id="selectCarAll"的SQL语句,但是它们的namespace前缀相同MyBatis可以区分

<!--CarMapper.xml-->
<mapper namespace="car">
     <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>

<!--CarMapper2.xml-->
<mapper namespace="car2">
     <!--sqlid重名了-->
     <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>

执行SQL语句使用SQL映射文件中的命名空间作为sqlid前缀

@Test
public void testNamespace(){
    // 获取SqlSession对象
    SqlSession sqlSession = SqlSessionUtil.openSession();

    // 执⾏SQL语句时的完整写法namespace.id
    List<Object> cars = sqlSession.selectList("car.selectCarAll");
    List<Object> cars = sqlSession.selectList("car2.selectCarAll");

    // 输出结果
    cars.forEach(car -> System.out.println(car));
}

原文地址:https://blog.csdn.net/qq_57005976/article/details/134763214

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_36418.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注