02-MyBatis的SQL映射文件的配置

SQL映射文件

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

mapper的namespace属性

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

  • sqlid的完整写法namespace.id: 使用命名空间namespace作为sqlid前缀可以防⽌不同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));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值