- 作用:实现创建一个接口后把mapper.xml由mybatis生成接口的实现类;通过调用接口对象就可以获取mapper.xml中编写的Sql。
- mybatis和spring整合时使用的就是这个方案。
- 实现步骤:
(1)创建一个接口。第一:接口包名和接口名与mapper.xml中<mapper>namespace相同。第二,接口中方法名和mapper.xml标签的id属性相同。
(2)在mybatis.xml中使用<package>进行扫描接口和mapper.xml
- 代码实现步骤:
(1)在mybatis.xml中<mappers>下使用<package>
<mappers>
<package name="com.ouc.mapper"/>
</mappers>
(2)在com.ouc.mapper下新建接口
public interface FlowerMapper {
List<Flower> selAll();
}
(3)在com.ouc.mapper下新建一个FlowerMapper.xml
其中:
①namespace必须和接口全限定路径(包名+类名)一致。
②id值必须和接口中方法名相同。
③如果接口中方法为多个参数,可以省略parameterType。
<mapper namespace="com.ouc.mapper.FlowerMapper">
<select id="selAll" resultType="flower">
select * from flower
</select>
</mapper>
本文详细介绍如何将MyBatis与Spring框架整合,实现通过接口调用映射文件中的SQL语句。具体步骤包括创建接口、配置mybatis.xml进行扫描、确保namespace和id属性与接口匹配。此方案为MyBatis与Spring结合的常用实践。
1282

被折叠的 条评论
为什么被折叠?



