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



    
    

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


<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>


<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>

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

你可能感兴趣的:(#,MyBatis的配置文件,mybatis,sql,java,JDBC)