1、SysUserMapper.java
package com.atguigu.schedule.mapper; import com.atguigu.schedule.pojo.SysUser; import org.springframework.stereotype.Repository; @Repository public interface SysUserMapper { SysUser getSysUser(SysUser sysUser); }
2、ScheduleMapper.java
package com.atguigu.schedule.mapper; import com.atguigu.schedule.pojo.Schedule; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface ScheduleMapper { List<Schedule> getScheduleList(Integer sysUserId); }
3、mapper/SysUserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace等于mapper接口类的全限定名,这样实现对应 --> <mapper namespace="com.atguigu.schedule.mapper.SysUserMapper"> <select id="getSysUser" resultType="SysUser"> select * from sys_user where username = #{username} and userPwd = #{userPwd} </select> </mapper>
4、mapper/ScheduleMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace等于mapper接口类的全限定名,这样实现对应 --> <mapper namespace="com.atguigu.schedule.mapper.ScheduleMapper"> <select id="getScheduleList" resultType="Schedule"> select * from sys_schedule where uid = #{value} </select> </mapper>
在MyBatis中,mapper中的namespace并不是可以随便写的。namespace在MyBatis中起到了唯一标识mapper的作用,它通常与mapper文件的名字相同,并且是全限定名(包含包名)。
在配置文件中定义mapper时,需要指定mapper的namespace,这个namespace应该与mapper文件中的namespace一致。例如,如果mapper文件名为UserMapper.xml,并且位于com.example.mapper包下,那么在配置文件中应该使用如下方式引用该mapper:
<mappers> <mapper resource="com/example/mapper/UserMapper.xml"/> </mappers>
而在UserMapper.xml文件中,应该使用如下方式指定namespace:
<mapper namespace="com.example.mapper.UserMapper"> <!-- 映射语句 --> </mapper>
如果namespace与文件名不一致,将会导致无法正确地加载和使用mapper。因此,建议在定义mapper时,将namespace与文件名保持一致,以确保正确性。