Mybatis的第三方通用类库通用Mapper 提供了简易的直接进行查询的方式,只需要继承指定的父类,调用其相应的方法,即可完成增删改查的基础操作,但只限于单表,下面来看一下是如何进行配置的。
常用的父类及其方法
- SelectOneMapper (selectOne)
- SelectMapper (select)
- SelectAllMapper (selectAll)
- SelectCountMapper (selectCount)
- SelectByPrimaryKeyMapper (selectByPrimaryKey)
- UpdateByPrimaryKeyMapper (updateByPrimaryKey)
- UpdateByPrimaryKeySelectiveMapper (updateByPrimaryKeySelective)
- DeleteMapper (delete)
- DeleteByPrimaryKeyMapper (deleteByPrimaryKey)
- InsertMapper (insert)
- InsertSelective (insertSelective)
- SelectByConditionMapper (selectByCondition)
- SelectCountByConditionMapper (selectCountByCondition)
- DeleteByConditionMapper (deleteByCondition)
- UpdateByConditionMapper (updateByCondition)
- UpdateByConditionSelectiveMapper (updateByCondition)
可以看到MyBatis提供的接口是非常的丰富的,但是如果我们只是需要指定的一些查询,而不需要另外的一些,实现这些接口是非常麻烦的,这种情况下,我们可以自定义一个通用的接口类,例如BaseMapper,让这个接口去继承需要的接口,从而简化开发。
public interface BaseMapper<T> extends BaseSelectMapper<T>, BaseUpdateMapper<T>, BaseDeleteMapper<T>, SqlServerMapper<T>,
ConditionMapper<T>, RowBoundsMapper<T>
Mapper3支持泛型查询,在泛型中指定要查询的实体类即可。
最后需要在Spring XML中进行配置:
<bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="base" value="com.xxx.xxx.mapper" />
<property name="markerInterface" value="com.xxx.xxx.mapper.BaseMapper" />
<property name="properties">
<value>
mappers=com.xxx.xxx.mapper.BaseMapper
</value>
</property>
</bean>
basePackage是用来指定Mapper接口文件所在的基包的,在这个基包或其所有子包下面的Mapper接口都将被搜索到。
markerInterface是用于指定一个接口的,当指定了markerInterface之后,MapperScannerConfigurer将只注册继承自markerInterface的接口。
properties是指mapper插件的配置,可以指定自己的mapper,也可以使用通用的mapper配置。
<property name="properties">
<value>
mappers=tk.mybatis.mapper.common.BaseMapper
</value>
</property>
就此,Mybatis的通用Mapper配置就完成了,在程序中可以直接调用mapper中接口的通用方法进行增删改查的操作。
注意一点,此通用mapper查询只支持单表的增删改查操作,如果需要进行复杂查询,仍需自行编写xml文件或使用注解的方式。