导包
Spring整合MyBatis除了导入Spring核心包外,还需要导入MyBatis所需要的所有包和MyBatis整合包。
整合MyBatis
Spring整合MyBatis主要是要简化MyBatis,提高开发效率,这就需要将原本需要程序员手动配置和编写的部分交由Spring管理。
配置数据库变量
首先,使用MyBatis需要先编写mybatis.xml全局配置文件,在全局配置文件中最主要的是需要配置数据库变量。
在Spring整合jdbc的jar包中有一个叫DriverManagerDataSource的类,它是Spring对于标准jdbc(javax.sql.DataSource)的简单实现,可以通过bean标签来配置一个DriverManager(java.sql.DriverManager),并且为每次的getConnection调用返回一个新的数据库连接。
在DriverManagerDataSource类中有一个叫setDriverClassName()的方法用于设置数据库连接驱动类名。
另外它还继承了抽象类AbstractDriverBasedDataSource。
在AbstractDriverBasedDataSource类中有属性url、username和password分别对应于数据库连接url、username和password。
通过Spring源码发现,配置数据库变量可以通过类DriverManagerDataSource来实现,所以我们需要在Spring配置文件中新建一个bean来创建DriverManagerDataSource对象。
配置SqlSessionFactory
配置完数据库变量后,使用mybatis需要创建SqlSessionFactory对象,再通过SqlSessionFactory对象来生产SqlSession。
这些步骤也可以交由Spring框架管理,在MyBatis与Spring的整合包中,有一个org.mybatis.spring.SqlSessionFactoryBean类对应于MyBatis中的SqlSessionFactory,所以我们也需要配置一个bean标签用于创建SqlSessionFactory对象。
SqlSessionFactoryBean中有一个DataSource类型的属性,我们需要给它传入前面创建的bean,DriverManagerDataSource就实现了DataSource接口。
配置Mapper扫描器
接下来原MyBatis全局配置文件中的内容还剩扫描mapper文件的部分。
在MyBatis与Spring的整合包中org.mybatis.spring.mapper.MapperScannerConfigurer对应着MyBatis全局配置文件中<package>
标签。
需要设置包路径和sqlSessionFactory对象。
到此为止,Spring配置文件的全部内容如下:
<?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">
<!-- 数据源封装类 .数据源:获取数据库连接,spring-jdbc.jar中-->
<bean id="dataSouce" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 创建SqlSessionFactory对象 -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接信息来源于dataSource -->
<property name="dataSource" ref="dataSouce"></property>
</bean>
<!-- 扫描器相当于mybatis.xml中 mappers下package标签,扫描com.test.mapper包后会给对应接口创建对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 要扫描哪个包 -->
<property name="basePackage" value="com.test.mapper"></property>
<!-- 和factory产生关系 -->
<property name="sqlSessionFactory" ref="factory"></property>
</bean>
</beans>
编写Mapper
接下来我们需要编写sql语句映射,使用Spring整合MyBatis一定需要使用“MyBatis接口绑定方案”,即需要每个为Mapper文件创建一个接口。
这里不写mapper文件直接在接口中使用注解。
package com.test.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import com.test.pojo.Airport;
public interface AirportMapper {
@Select("select * from airport")
List<Airport> selAll();
}
编写Service
编写Service接口和实现
package com.test.service;
import java.util.List;
import com.test.pojo.Airport;
public interface AirportService {
List<Airport> show();
}
package com.test.service.impl;
import java.util.List;
import com.test.mapper.AirportMapper;
import com.test.pojo.Airport;
import com.test.service.AirportService;
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();
}
}
在servlet中会需要实例化service实现类对象,所以也可以将其交由Spring管理。
至此Spring配置文件就已经编写完成了:
<?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">
<!-- 数据源封装类 .数据源:获取数据库连接,spring-jdbc.jar中-->
<bean id="dataSouce" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 创建SqlSessionFactory对象 -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接信息来源于dataSource -->
<property name="dataSource" ref="dataSouce"></property>
</bean>
<!-- 扫描器相当于mybatis.xml中 mappers下package标签,扫描com.test.mapper包后会给对应接口创建对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 要扫描哪个包 -->
<property name="basePackage" value="com.test.mapper"></property>
<!-- 和factory产生关系 -->
<property name="sqlSessionFactory" ref="factory"></property>
</bean>
<!-- 由spring管理service实现类 -->
<bean id="airportService" class="com.test.service.impl.AirportServiceImpl">
<property name="airportMapper" ref="airportMapper"></property>
</bean>
</beans>
编写Servlet
Spring没法管理Servlet,Servlet由Tomcat管理。
Spring整合web项目时的思路是:当服务启动时(tomcat),通过监听器将SpringIOC容器初始化一次(该监听器 spring-web.jar已经提供),web项目启动时 ,会自动加载web.xml,因此需要在web.xml中加载监听器(ioc容器初始化)。
所谓的ioc容器其实相当于applicationContext.xml配置文件,把所有被ioc管理的对象放入其中,放入bean标签里,当做对象管理。
所以我们首先指定我们需要加载的Spring配置文件,在tomcat容器启动后,会寻找项目中的web.xml文件,加载其中的信息,并创建一个ServletContext上下文对象,以后再web应用中可以获得其中的值。
随后需要配置监听器,监听器的作用是监听ServletContext的对象是否创建,web容器一旦启动,就会创建一个ServletContext对象,所以监听器一定会触发,从而执行监听器的contextInitialized方法。
完整的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代码如下,需要在init方法中初始化ApplicationContext,再获取到Service对象。随后在Servlet的Service方法中编写控制器逻辑。
package com.test.servlet;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.test.service.AirportService;
import com.test.service.impl.AirportServiceImpl;
@WebServlet("/airport")
public class AirportServlet extends HttpServlet{
private AirportService airportService;
@Override
public void init() throws ServletException {
//对service实例化
// ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//spring和web整合后所有信息都存放在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);
}
}
至此一个Spring整合MyBatis的后台demo项目就完成了。