介绍:
本文介绍Spring整合Mybatis,前置条件:Spring+SpringMVC+Mybatis+Maven。
Spring和Maven的相关知识可以参考上一篇文章:利用Maven和SpringMvc搭建javaweb工程。
目的
实现查询系统Banner图列表
步骤
- 1、添加pom.xml依赖(本文采用1.3版本,采用2.0版本的可能不同)
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
- 2、修改SpringXML配置文件,添加以下内容,具体路径需要根据各自项目配置。
<!--创建一个sql会话工厂bean,指定数据源-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource" /><!-- 指定数据源 -->
<!-- 类型别名包,默认引入bean下的所有类 -->
<property name="typeAliasesPackage" value="com.bean"/>
<!-- 指定sql映射xml文件的路径 -->
<property name="mapperLocations" value="classpath:com/mapper/*.xml"/>
</bean>
<!--自动扫描映射接口-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定sql会话工厂,在上面配置过的 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 指定基础包,即自动扫描com.mapper这个包以及它的子包下的所有映射接口类 -->
<property name="basePackage" value="com.mapper"/>
</bean>
- 3、增加BannerMapper.XML。
<?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="com.mapper.BannerMapper">
<select id="list" resultType="BannerEntity">
select * from sys_banner
</select>
</mapper>
- 4、增加BannerMapper接口类
package com.mapper;
import com.bean.BannerEntity;
import javax.annotation.Resource;
import java.util.List;
@Resource
public interface BannerMapper {
List<BannerEntity> list();
}
- 5、增加BannerService接口类
package com.service;
import com.bean.BannerEntity;
import java.util.List;
public interface BannerService {
List<BannerEntity> list();
}
- 6、增加BannerServiceImpl接口实现类
package com.service;
import com.bean.BannerEntity;
import com.mapper.BannerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("bannerService")
public class BannerServiceImpl implements BannerService {
@Autowired
private BannerMapper bannerMapper;
public List<BannerEntity> list(){
return bannerMapper.list();
}
}
- 7、BannerController类中新增方法
//Banner图列表
@RequestMapping("/bannerList_test.do")
@ResponseBody
public JsonResult<BannerEntity> bannerList_test() {
List<BannerEntity> res = bannerService.list();
JsonResult<BannerEntity> result=new JsonResult<>();
result.setList(res);
return result;
}
- 8、新增BannerEntity实体类
@Data
public class BannerEntity {
private String id;
private String img_base64;
private String sort;
private String content;
private String web_url;
}
测试
请求该方法返回值如下:

返回Json结果
至此,Spring整合Mybatis成功,数据请求正确!