一、使用 Spring 简化 MyBatis
1、导 入 mybatis 所 有 jar 和 spring 基 本包,spring-jdbc、spring-tx、spring-aop、spring-web、spring 整合 mybatis 的包等。

2、先配置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>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.Con
textLoaderListener</listener-class>
</listener>
</web-app>
3、编写 spring 配置文件 applicationContext.xml
<?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/ssm"></property>
<property name="username" value="root"></property>
<property name="password" value="smallming"></property>
</bean>
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSouce"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.jax.mapper"></property>
<property name="sqlSessionFactory" ref="factory"></property>
</bean>
<bean id="airportService" class="com.jax.service.impl.AirportServiceImpl">
<property name="airportMapper" ref="airportMapper"></property>
</bean>
</beans>
4、编写代码
- 正常编写 pojo
- 编写 mapper 包下时必须使用接口绑定方案或注解方案(必须有接口)。
- 正常编写 Service 接口和 Service 实现类,需要在 Service 实现类中声明 Mapper
接口对象,并生成get/set 方法。 - spring 无法管理 Servlet,在 service 中取出 Servie 对象。
@WebServlet("/airport")
public class AirportServlet extends HttpServlet{
private AirportService airportService;
@Override
public void init() throws ServletException {
webApplicationContext ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
airportService=ac.getBean("airportService",AirportServiceImpl.class);
}
@Override
protected void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException {
req.setAttribute("list", airportService.show());
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
