Spring整合MyBatis
- 现在配置文件中配置 MyBatis 相关配置,如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 数据源封装类,数据源:获取数据库连接 -->
<bean id="dataSouce"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver"></property>
<property name="url"
value="jdbc:mysql://localhost:3306/spring"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 创建SqlSessionFactory对象 -->
<bean id="factory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSouce"></property>
</bean>
<!-- 扫描器相当于mybatis.xml中 mappers下package标签,扫描com.spring.mapper包后会给对应接口创建对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 要扫描哪个包 -->
<property name="basePackage" value="com.spring.mapper"></property>
<!-- 和factory产生关系 -->
<property name="sqlSessionFactory" ref="factory"></property>
</bean>
<!-- 由spring管理service实现类 -->
<bean id="airportService"
class="com.spring.service.impl.AirportServiceImpl">
<property name="airportMapper" ref="airportMapper"></property>
</bean>
</beans>
解析:
id | 作用 |
---|---|
dataSouce | 数据源封装类 。数据源:获取数据库连接,在spring-jdbc.jar中。 |
factory | 创建 SqlSessionFactory 对象。 |
MapperScannerConfigurer | 扫描器,会去扫描com.spring.mapper包后会给对应接口创建对象。 |
airportService | 由spring管理service实现类 |
注意:mapper 包下必须接口绑定方案或者注解方案(必须有接口)。
- 经过配置以后,再创建一个 Airport 类,如下:
public class Airport {
private int id;
private String portName;
private String cityName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPortName() {
return portName;
}
public void setPortName(String portName) {
this.portName = portName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
@Override
public String toString() {
return "Airport [id=" + id + ", portName=" + portName + ", cityName=" + cityName + "]";
}
}
- 写一个 Service 接口,如下:
public interface AirportService {
List<Airport> show();
}
- 实现 Service 接口类,如下:
public class AirportServiceImpl implements AirportService {
private AirportMapper airportMapper;
public AirportMapper getAirportMapper() {
return airportMapper;
}
public void setAirportMapper(AirportMapper airportMapper) {
this.airportMapper = airportMapper;
}
@Override
public List<Airport> show() {
return airportMapper.selAll();
}
}
- AirportMapper 类,如下:
public interface AirportMapper {
@Select("select * from airport")
List<Airport> selAll();
}
- 最后,测试代码,如下:
public class Test {
public static void main(String[] args) {
//ClassPathXmlApplicationContext 默认去classes文件夹根目录寻找
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
AirportServiceImpl bean = ac.getBean("airportService",AirportServiceImpl.class);
List<Airport> list = bean.show();
System.out.println(list);
}
}
- 最终运行结果如下:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UgF7h4UK-1576340047643)(E:\面试准备\Spring\img\spring_mybatis_test.png)]
Spring+MyBatis+Servlet
- 前面步骤已完成 Spring 整合 MyBatis 的步骤,下面继续整合Servlet。
- 首先,创建 Servlet 类,如下:
@WebServlet("/airport")
public class AirportServlet extends HttpServlet {
private AirportService airportService;
public void init() {
//对 service 实例化
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
airportService = ac.getBean("airportService",AirportServiceImpl.class);
}
protected void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("list",airportService.show());
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
- 此步骤即完成 Servlet 步骤,但是我们发现,此时仍然需要我们手动加载 applicationContext.xml 文件,如:
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
- 我们想让 Tomcat 加载的时候自动去加载 applicationContext.xml 文件,因此我们需要在 web.xml 写以下配置,如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- 上下文参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- spring配置文件 -->
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 封装了一个监听器,帮助加载Spring的配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
- 因此,我们在 Servlet 中需要更改为以下代码,如下:
@WebServlet("/airport")
public class AirportServlet extends HttpServlet {
private AirportService airportService;
public void init() {
//ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//spring和web整合后所有信息都存放在webApplicationContext
ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
//对 service 实例化
airportService = ac.getBean("airportService",AirportServiceImpl.class);
}
protected void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("list",airportService.show());
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
-
即原本的:
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
-
更改为:
ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
-
最后实现页面,如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:forEach items="${list }" var="a">
${a.id } ${a.portName } ${a.cityName }<br/>
</c:forEach>
</body>
</html>
- 运行结果如下: