介紹:
本文介紹Spring整合Mybatis,前置條件:Spring+SpringMVC+Mybatis+Maven。
Spring和Maven的相關(guān)知識(shí)可以參考上一篇文章:利用Maven和SpringMvc搭建javaweb工程。
目的
實(shí)現(xiàn)查詢系統(tǒng)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配置文件,添加以下內(nèi)容,具體路徑需要根據(jù)各自項(xiàng)目配置。
<!--創(chuàng)建一個(gè)sql會(huì)話工廠bean,指定數(shù)據(jù)源-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource" /><!-- 指定數(shù)據(jù)源 -->
<!-- 類型別名包,默認(rèn)引入bean下的所有類 -->
<property name="typeAliasesPackage" value="com.bean"/>
<!-- 指定sql映射xml文件的路徑 -->
<property name="mapperLocations" value="classpath:com/mapper/*.xml"/>
</bean>
<!--自動(dòng)掃描映射接口-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定sql會(huì)話工廠,在上面配置過的 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 指定基礎(chǔ)包,即自動(dòng)掃描com.mapper這個(gè)包以及它的子包下的所有映射接口類 -->
<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接口實(shí)現(xiàn)類
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實(shí)體類
@Data
public class BannerEntity {
private String id;
private String img_base64;
private String sort;
private String content;
private String web_url;
}
測(cè)試
請(qǐng)求該方法返回值如下:

返回Json結(jié)果
至此,Spring整合Mybatis成功,數(shù)據(jù)請(qǐng)求正確!