上一篇我们简单的讲解了Spring和MyBatis的整合,但你不难发现,其配置起来还是够麻烦的。最明显的一点是,我们需要在自定义的Mapper接口写个很长的SQL注解,并且还要手动注册到Spring容器。本文主要讲解简化的方法。
首先,还是定义接口,但你已看不到任何框架的痕迹,
package org.chen.mybatis.mapper; import org.chen.domain.Spitter; public interface SpitterMapper { Spitter getSpitter(String email); }
文件SpitterMapper的名字必须和上面的接口同名。SpitterMapper的内容如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="org.chen.mybatis.mapper.SpitterMapper"> <select id="getSpitter" resultType="org.chen.domain.Spitter"> select * from spitter where email = #{email} </select> </mapper>
接下来在Spring配置文件里,
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="org.chen.mybatis.mapper" /> </bean>
为了简化上面的resultType的书写,
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="org.chen.domain" /> </bean>
最后我们向service注入Mapper,
@Service public class TestService { @Autowired private SpitterMapper spitterMapper; public void setSpitterMapper(SpitterMapper spitterMapper) { this.spitterMapper = spitterMapper; }
原文地址:http://blog.csdn.net/chenloveit/article/details/38869557