目的:1、解决原生硬编码的问题
2、便于后期执行sql
好处:首先他不依赖于字符串字面值,会更安全一点;其次,你的IDE有代码补全功能,那么代码补全可以帮你快速选择到映射好的sql语句
步骤:
1、定义与SQL映射文件同名的Mapper接口,并且将Mapper接口与SQL映射文件放置同一目录下
在包下创建接口UserMapper;在resources下创建目录和UserMapper的目录一致
注意:在resources下创建包的层次结构用“/"作为分割符号
2、设置SQL映射文件namespace属性为Mapper接口全限定名
之前:
<mapper namespace="test"> <!--namespace:名称空间--> <select id="selectAll" resultType="com.itheima.pojo.User"> select * from tb_User; </select> </mapper>
修改之后:
<mapper namespace="com.itheima.mapper.UserMapper"> <select id="selectAll" resultType="com.itheima.pojo.User"> select * from tb_User; </select> </mapper>
3、在Mapper接口中定义方法,方法名就是SQL映射文件中的sql语句的id,并保持参数值类型和返回值类型一致
List<User> selectAll();
更改mybatis-config.xml中的mapper路径
<mappers> <mapper resource="com/itheima/mapper/UserMapper.xml"/> </mappers>
4、编码
1.通过SqlSession的getMapper方法获取Mapper接口的代理对象
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
2.通过对应方法完成sql的执行
List<User> users= userMapper.select();
System.out.println(users);
sql.Session.close();//释放资源