如果使用hiberante作為dao層,常用的方式是:定義一個dao層接口包(com.dao.service)然后在定義一個dao層接口實現包(com.dao.service.impl),這樣定義結構清晰,方便維護和開發工作。如果使用mybatis作為dao層,就可以省略到dao實現包,直接將sql實現在xml配置文件中編寫,這樣可以直接通過接口訪問映射文件。本文介紹模型層的這兩種設計模式。
一、設計模式一:由接口訪問映射文件
如采取此種設計模式,需要:
一、在spring-mybatis的配置文件中配置MapperScannerConfiguer:這是將sqlSessionFactory注入到指定包中的java類中。
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.shyy.web.service"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean>
二、映射文件的命名空間設置為指定接口,如:com.shyy.web.service.TreeMapper是訪問該映射文件的接口名稱。
<mapper namespace="com.shyy.web.service.TreeMapper" >
三、接口中的方法必須和映射文件一致。如:
映射文件中的某sql:
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" > select <include refid="Base_Column_List" /> from t_tree where tid = #{tid,jdbcType=VARCHAR} </select>
接口中對應的方法名:
Student selectByPrimaryKey(Integer sid);
需要訪問映射文件的sql,只需在當前類注入相應的接口:

需注意的是,由於該接口沒有實現類,所以在如idea上會報這樣的提示,說不能注入,因為接口是不能實例化的,在eclipse上不會報,但實際上沒有影響。
設計模式2:由接口的實現類訪問映射文件
示例接口:
package com.shyy.web.service; import com.shyy.web.entity.Student; public interface StudentMapper { int deleteByPrimaryKey(Integer sid); int insert(Student record); int insertSelective(Student record); Student selectByPrimaryKey(Integer sid); int updateByPrimaryKeySelective(Student record); int updateByPrimaryKey(Student record); }
其實現類:
package com.shyy.web.service.impl; import com.shyy.web.entity.Student; import com.shyy.web.service.StudentMapper; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository("studentMapperImpl") public class StudentMapperImpl implements StudentMapper { @Autowired protected SqlSessionTemplate session; public StudentMapperImpl() { } //獲取接口名 private String clazz = this.getClass().getInterfaces()[0].getName(); public int deleteByPrimaryKey(Integer sid) { return session.delete(clazz+".deleteByPrimaryKey",sid); } public int insert(Student record) { return session.insert(clazz+".insert",record); } public int insertSelective(Student record) { return session.insert(clazz+".insertSelective",record); } public Student selectByPrimaryKey(Integer sid) { return session.selectOne(clazz+".selectByPrimaryKey",sid); } public int updateByPrimaryKeySelective(Student record) { return session.update(clazz+".updateByPrimaryKeySelective",record); } public int updateByPrimaryKey(Student record) { return session.update(clazz+".updateByPrimaryKey",record); } }
這樣的設計模式需要在實現類中注入SqlSessionTemplate ,所以spring-mybatis的配置文件應該加上:
<!-- 獲取SqlSessionTemplate --> <bean class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg ref="sqlSessionFactory"></constructor-arg> </bean>
需要由此接口的實現類訪問映射文件,則在注入時接口的引用名要與@Repository("studentMapperImpl")中的名字一致:
@Autowired
private StudentMapper studentMapperImpl;
這樣就相當於實例化了接口StudentMapper 的實現類StudentMapperImpl 。
