mybatis映射器机制,我们只需要定义好借口,mybatis帮我创建实现类,并且来管理SqlSession对象的创建和关闭,减少我们不少工作。缺点能就是不太够灵活。mybatis映射器注入可以选择两种方式,一种依赖MapperFactoryBean,另外一种方式依赖MapperScannerConfigure。
MapperFactoryBean
首先定义一个映射器,映射器是一个接口
public interface MusicMapper {
/**
*
* @description TODO
* @param id
* @return
* @return Music
*/
@Results(id = "musicResult", value = {
@Result(property = "id", column = "id", id = true),
@Result(property = "name", column = "name"),
@Result(property = "singer", column = "singer"),
@Result(property = "album", column = "album"),
@Result(property = "duration", column = "duration"),
@Result(property = "author", column = "author"),
@Result(property = "composer", column = "composer"),
@Result(property = "style", column = "style") })
@Select("select * from t_music where id= #{id}")
public Music getMusicById(@Param("id") String id);
/**
* id; name; singer;
*
* album; duration; author; composer;style
*/
}
在Spring配置映射器,要将映射器注入到Service实现类中
<bean id="musicMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="org.lian.mapper.MusicMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="musicService" class="org.lian.service.impl.MusicServiceImpl">
<property name="musicMapper" ref="musicMapper"/>
</bean>
当映射器很多的时候,像上面的配置似乎会让配置显得更加臃肿,那么采用下面的方式就可以简化上面的配置
MapperScannerConfigure
采用下面的配置可以省略配置很多Mapper映射器
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--如果是多个包 org.lian.dao;org.lian.mapper;...;*
org.lian.dao,org.lian.mapper....,* 使用,或者;分隔-->
<property name="basePackage" value="org.lian.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<bean id="musicService" class="org.lian.service.impl.MusicServiceImpl">
<property name="musicMapper" ref="musicMapper"/>
</bean>
采用上面的方式有一个要求就musicMapper要和映射器接口MusicMapper要保持一致,如果想要更加灵活可以使用Spring的@Component或者JSR-330 的@Named 注解,Spring其他注解没有测试,除此之外还有其他的注解那需要配置MapperScannerConfigure的annotationClass 属性指定了要寻找的注解名称。
@Component("groupDao")
public interface GroupMapper {
@Results(id = "groupResult", value = {
@Result(property = "groupId", column = "group_id", id = true),
@Result(property = "groupName", column = "group_name") })
@Select("select * from t_group where group_id= #{groupId} ")
public Group getGroupById(String groupId);
}
@Service("groupService")
public class GroupServiceImpl implements GroupService {
private GroupMapper groupDao;
@Override
public Group getGroupById(String groupId) {
return groupDao.getGroupById(groupId);
}
public GroupMapper getGroupDao() {
return groupDao;
}
@Resource(name = "groupDao")
public void setGroupDao(GroupMapper groupDao) {
this.groupDao = groupDao;
}
}
Spring整合mybatis官网给出了更加详尽的内容,需要的查询的可以参考Spring-mybatis官网
本文介绍如何在Spring中整合Mybatis并进行映射器注入,包括使用MapperFactoryBean和MapperScannerConfigurer两种方式。通过MapperFactoryBean,需要在Spring配置文件中为每个映射器接口进行配置。而MapperScannerConfigurer则可以简化配置,只需确保接口名与映射器名称匹配。此外,还可以使用@Component或JSR-330的@Named注解增加灵活性。更多详细信息可参考Spring-Mybatis官方文档。
2万+

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



