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.xml
和CarMapper2.xml
<!--引入sql映射文件-->
<mappers>
<mapper resource="CarMapper.xml"/>
<mapper resource="CarMapper2.xml"/>
</mappers>
CarMapper.xml
和CarMapper2.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));
}