标签:
如果使用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上不会报,但实际上没有影响。
示例接口:
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 。
标签:
原文地址:http://www.cnblogs.com/chenxueling/p/5474767.html