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

发表回复

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