前言
经过技术的层层迭代,现在已经是Spring的天下了,而Spring有整合Mybatis自己的一套模式,和以前我们不再需要confige.xml和Mapper.xml,Spring会在applicationContext.xml中配置好SqlsessionFactory,并且自动生成对象,我们看看之前的Mybatis和今天经过整合后的Mybatis有什么异同
一 过去Servlet+Mybatis
我们主要研究过去是怎么拿session和现在有什么区别
环境:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
Resource目录
当时的config.xml还十分朴素…
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--连接数据库的信息-->
<properties resource="db.properties"/>
<!--日志文件-->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<!--别名-->
<typeAliases>
<package name="com.etoak.student.entity"/>
</typeAliases>
<!--配置dataSource-->
<environments default="m">
<environment id="m">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${pwd}"/>
</dataSource>
</environment>
</environments>
<!--加载Mapper-->
<mappers>
<mapper resource="StudentMapper.xml"></mapper>
</mappers>
</configuration>
所以我们根据dataSource需要的value 配置db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/et2009
user=root
pwd=etoak
然后我们Mapper.xml放我们项目需要的sql语句,它会映射一个Mapper的接口比如这样👇
这是Mapper.xml里面的namespace,
而它会去这个路径映射这个接口
对应的方式:Mapper.xml中的sql语句的id对应Mappe接口方法名字,比如:
对应的接口
我们看看它整套流程
至于代码:SQL Session Factory工厂,过去我们会这么写
public class SF {
private static SqlSessionFactory f =null;
private SF(){}
static{
try{
Reader reader = Resources.getResourceAsReader("config.xml");
f=new SqlSessionFactoryBuilder().build(reader);
}catch (Exception e){
e.printStackTrace();
}
}
public static SqlSession getConnection(){
return f.openSession();
}
}
可以看到 SqlSessionFactoryBuilder拿着Resources读config.xml的字符流new了一个对象,这个对象就是SqlSessionFactory,我们Service获取Session,就是调用getConnection()这个方法
部分Service代码👇
这里就是我这个图中的这个部分👇
这是过去Servlet和Mybatis搭配使用的流程
二 Spring+Mybatis
正如我说现在是Spring的天下了,那么我们看看Spring整合Mybatis做了哪些优化,applicationContext.xml直接配置好了Session工厂
下面是root容器的的代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
">
<context:component-scan base-package="com.etoak">
<!--扫描@Service @Repository注解-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
<!--排除@Controller @RestController-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController"/>
</context:component-scan>
<!--导入db.properties-->
<context:property-placeholder location="classpath:db.properties" />
<!--数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<!--SqlSessionFactoryBean******-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!--sqlSessionFactory需要一个数据源 我们无法直接操作SqlSessionFactory所以只能在这里引入数据源-->
<property name="dataSource" ref="dataSource" />
<!--别名-->
<property name="typeAliasesPackage" value="com.etoak.bean" />
<!--Mapper-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
<!--分页插件-->
<property name="plugins">
<list>
<bean class="com.github.pagehelper.PageInterceptor" />
</list>
</property>
</bean>
<!--扫描指定包下的mapper接口 为接口创建代理对象 并将代理对象注册到Spring容器中 也就是不需要再去写@Repository-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--为这个包下创建代理对象-->
<property name="basePackage" value="com.etoak.mapper"/>
</bean>
</beans>
它顶替了原本config.xml,当然db.properties还是需要的
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/et2009
db.username=root
db.password=etoak
和上面这个地方对应
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
而Spring还有一个SpringMVC容器 负责管理处理器也就是我们的Controller
配置一些处理器映射器,处理器适配器等等一些东西SpringMVC容器详解
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
">
<context:component-scan base-package="com.etoak">
<!--扫描@Controller @RestController-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController"/>
<!--忽略下面两个@Service @Repository-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan><!--扫描@Controller自动找配置器-->
<mvc:annotation-driven/><!--3种处理器映射器 3种处理器适配器-->
<mvc:default-servlet-handler/><!--静态资源加载-->
<!-- 视图解析器 它和thymleaf冲突 选一个用 这里我需要解析html所以用了thymleaf jsp就注释下面
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsps/"/>
<property name="suffix" value=".jsp"/>
</bean>-->
<!--thymleaf模板引擎-->
<!--SpringResourceTemplateResolver-->
<bean id="templateResolver" class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/templates/"/><!--位置-->
<property name="suffix" value=".html"/><!--后缀-->
<property name="templateMode" value="HTML"/><!--模板类型-->
<property name="characterEncoding" value="UTF-8"/><!--页面编码-->
<property name="cacheable" value="false"/><!--是否缓存页面-->
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine"/>
<property name="characterEncoding" value="UTF-8"/><!--页面编码-->
</bean>
</beans>
ok还需要在web.xml里配置Springmvc,并且添加Filter解决前端来的中文乱码问题
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>forEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
就不再需要自己去getSession,也不需要自己获得Mapper的对象,有了SpringMvc也不再需要Servlet,过去冗杂的流程变得十分简单👇
顺着这条线我们看看代码
首先是Controller(原Servlet)
@Controller
public class PublisherController {
@Autowired//自动bytype生成对象
private PublisherService service;
@RequestMapping(value = "/queryAllPubs",method = RequestMethod.POST)
@ResponseBody
public ETResponse queryAllPublishers(){
//调用service
List<Publisher> pubs =service.queryAllPubs();
//查询所有的
ETResponse response =new ETResponse();
response.setCode(ETEnums.SUCCESS.getCode());//自己写了一个枚举 类似于"200"
response.setMsg(ETEnums.SUCCESS.getMsg());//"查询成功与否"
response.setData(pubs);
return response;
}
}
接着是Service
@Service
public class PublisherService {
@Autowired//自动生成
private PublisherMapper dao;
public List<Publisher> queryAllPubs(){
//Controller-->Service-->mapper 防止依赖循环
return dao.queryAllPubs();
}
}
这里我用的父子工程,Controller Service Mapper都各自是一个Moudel所以需要导入相互的依赖
这里会遇到一个问题需要说一下,
什么是依赖的循环,我们的Controller,Service,和Mapper只能按B导入C,A导入B的顺序,否则会成一个圈
正确的打开方式
Service导Mapper的依赖:
<dependency>
<groupId>org.example</groupId>
<artifactId>book-mapper</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
Controller导入Service依赖
<dependency>
<groupId>org.example</groupId>
<artifactId>book-service</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
有时报错就是因为下面这种场景
要的Service依赖Mapper Controller依赖Service 不要成环!
Mapper(原dao)
因为我们在applicationContext.xml里面写了Mapper的自动扫描
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.etoak"></property>
</bean>
所以不需要加@Repository
public interface PublisherMapper {
List<Publisher> queryAllPubs();//下拉框 显示所有出版社
}
然后会去直接找接口映射的mapper.xml文件执行sql语句
然后顺着这条线返回给Controller 将装配好的实体类对象返回给客户端
总结
说了不少,其实两者的本质区别,就在于Spring中IOC如何自动管理SqlSessionFactoryBean?我在这篇文章有讲述👉SpringIOC详解可以移步看一下
最后想说:在技术不断变迁的今天,只有通透以往技术点哪里不足的人才能鱼跃