SpringMVC和MyBatis整合入门

1. 整合思路

  • 表现层 SpringMVC
  • 业务层 service接口
  • 持久层 MyBatis

Spring将各层进行整合

  • 通过spring管理持久层的mapper(相当于dao接口)
  • 通过spring管理业务层service,service中可以调用mapper接口。
  • spring进行事务控制。
  • 通过spring管理表现层Handler,Handler中可以调用service接口。

mapper、service、Handler都是javabean(Java组件)。Spring的IOC和AOP特性很容易做到上面这些

2. 整合思路

  • 第一步:整合dao层

​ mybatis和spring整合,通过spring管理mapper接口。

​ 使用mapper的扫描器自动扫描mapper接口在spring中进行注册。

  • 第二步:整合service层

​ 通过spring管理 service接口。

​ 使用配置方式将service接口配置在spring配置文件中。

​ 实现事务控制。

  • 第三步:整合springmvc

​ 由于springmvc是spring的模块,不需要整合。

3. 整合过程,基于maven

3.1 整合dao层

创建配置文件applicationContext-dao.xml配置文件,里面专门放置跟dao层相关的配置

applicationContext-dao.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--加载属性文件-->
<context:property-placeholder location="classpath:config.properties"/>

<!--
使用自动扫描:将mybatis的mapper自动装载进来
遵循的规范:mapper.java和mapper.xml映射文件名保持一致,并且要在一个目录中
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.lee.ssm.mapper"/>
</bean>

<!--配置数据源-->
<!--配置c3p0连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--数据库连接相关信息-->
<property name="driverClass" value="${jdbc.driverClassName}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>

<!--使用SqlSessionFactoryBean来代替SqlSessionFactoryBuilder创建SqlSessionFactory,&ndash;&gt;-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--加载MyBatis的配置文件-->
<property name="configLocation" value="classpath:mybatis/mybatis_cfg.xml"/>
<!--配置数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>

要点:

  • 配置数据源
  • 配置SqlSessionFactoryBean,用于创建SqlSessionFactory
  • 配置mapper扫描器,用于将mapper自动加载出来
  • 可以使用mybatis的逆向工程生成单表的mapper

还需要一个文件,mybatis的配置文件mybatis_cfg.xml,里面用于放置mybatis的运行环境

mybatis_cfg.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?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>

<settings>
<setting name="logImpl" value="LOG4J"/>
<!--
配置懒加载:
lazyLoadingEnabled:
表示是否开启懒加载,true表示开启懒加载,默认为true
aggressiveLazyLoading:
当它为true的时候,访问任何一个属性,都会触发查询,懒加载的对象也会被查询
当它为false的时候,你访问了非懒加载对象,他不会执行懒加载语句;直到你访问了懒加载对象,他才会进行加载
默认值为true
lazyLoadTriggerMethods:
指定哪些对象的方法会触发一次延迟加载.默认有: equals,clone,hashCode,toString
当执行这些方法的时候,都会触发懒加载
-->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
<!--将触发懒加载的方法设成空-->
<setting name="lazyLoadTriggerMethods" value="/"/>

<!--开启二级缓存,默认就是true,可以不配置-->
<setting name="cacheEnabled" value="true"/>

</settings>

<!--批量设置别名-->
<typeAliases>
<package name="com.lee.ssm.model"/>
</typeAliases>

<!--在Spring中开启组件扫描,所以这里不用配置了
注意:在Spring中自动扫描Mapper.xml和Mapper.java必须要满足文件名一致,并且在同一个目录下-->
<!--<mappers></mappers>-->

</configuration>

3.2 整合service

BookService接口:

1
2
3
public interface BookService {
List<Book> findAllBooks() throws Exception;
}

BookService的实现类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class BookServiceImpl implements BookService {

private BookMapper mBookMapper;

public BookMapper getBookMapper() {
return mBookMapper;
}

// 自动注入BookMapper,Spring会自动装配
@Autowired
public void setBookMapper(BookMapper bookMapper) {
mBookMapper = bookMapper;
}

/**
* 查询所有的Book信息
*
* @return
* @throws Exception
*/
@Override
public List<Book> findAllBooks() throws Exception {
BookExample bookExample = new BookExample();
List<Book> bookList = mBookMapper.selectByExample(bookExample);
return bookList;
}
}

让spring管理我们的service,因此在applicationContext-service.xml中配置service的bean

applicationContext-service.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--book的Service-->
<bean id="bookService" class="com.lee.ssm2.service.impl.BookServiceImpl"/>
</beans>

3.3 事务控制

service层负责事务管理.

为了是xml配置文件分工明确,这里可以另外分离出一个applicationContext-transaction.xml配置文件:

applicationContext-transaction.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/tx/spring-aop.xsd">

<!--配置事务-->
<!--第一步:配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注意这个dataSource是引用自dao层映射文件中的-->
<property name="dataSource" ref="dataSource"/>
</bean>

<!--第二步:配置事务增强-->
<tx:advice id="tx_advice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="select*" propagation="REQUIRED"/>
<tx:method name="get*" propagation="REQUIRED"/>
<tx:method name="load*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>

<!--第三步:配置切面-->
<aop:config>
<aop:pointcut id="book_pointcut" expression="execution(* com.lee.ssm2.service.*.*(..))"/>
<aop:advisor advice-ref="tx_advice" pointcut-ref="book_pointcut"/>
</aop:config>

</beans>

3.4 整合SpringMVC

整合思路,一共有四个点:

  • 配置前端控制器(在web.xml中)

    web.xml:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <!--前端控制器配置-->
    <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载applicationContext-mvc配置文件-->
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <!--配置文件的地址如果不配置contextConfigLocation,默认查找的配置文件名称是classpath下的:servlet名称+"-servlet.xml"即springmvc-servlet.xml-->
    <param-value>classpath:spring/applicationContext-mvc.xml</param-value>
    </init-param>
    </servlet>
    <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!--
    可以配置"/"此工程所有的请求全部由springmvc解析,此种方式可以实现RESTful方式,需要特殊处理对静态文件的解析不能由springmvc解析;
    可以配置*.do或者*.action,所有请求的url扩展名为.do或.action由springmvc解析,此中方法常用;
    不可以配置"/*",如果配置/*,返回jsp也由springmvc解析,这是不对的
    -->
    <url-pattern>*.action</url-pattern>
    </servlet-mapping>
  • 配置处理器映射器(在applicationContext-mvc.xml中)(选择注解方式)

  • 配置处理器适配器(在applicationContext-mvc.xml中)(选择注解方式)

  • 配置视图解析器(在applicationContext-mvc.xml中)

    applicationContext-mvc.xml:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <?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.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--开启组件自动扫描-->
    <context:component-scan base-package="com.lee.ssm2.controller"/>

    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!--prefix表示jsp路径的前缀,suffix表示jsp路径的后缀-->
    <!--在实际的controller中路径jsp/index.jsp就可以直接简化成index-->
    <!--通过该视图解析器的解析,会自动的拼接真正的视图路径-->
    <property name="prefix" value="/jsp"/>
    <property name="suffix" value=".jsp"/>
    </bean>
    <!--================================================================================-->
    <!--使用注解的方式配置Handler以后,需要将处理器映射器和处理器适配器配置为以下的方式-->
    <!--配置处理器映射器-->
    <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>-->
    <!--配置处理器适配器-->
    <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>-->
    <!--一句话将处理器映射器和处理器配置器配置进来了,用来取代上面的两行代码-->
    <mvc:annotation-driven/>
    

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26



    ## 3.5 装载Spring容器

    回顾:上面一共有四个Spring相关的配置文件

    * `applicationContext-dao.xml`
    * `applicationContext-service.xml`
    * `applicationContext-transaction.xml`
    * `applicationContext-mvc.xml`

    其中`applicationContext.mvc.xml`是SpringMVC的配置文件,他已经在配置前端控制器的时候作为配置参数传递进去了.而另外三个是Spring容器加载需要的配置文件,因此他们也需要在`web.xml`文件中进行配置,配置如下:

    ​```xml
    <!--加载Spring容器-->
    <!--指定Spring配置文件的位置-->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <!--使用通配符的方式-->
    <param-value>classpath:spring/applicationContext-*.xml</param-value>
    </context-param>
    <!--配置Spring监听器-->
    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

其中:ContextLoaderListener是Spring上下文加载时的监听器,当它读取到context-param参数的时候,就会在服务器启动的时候创建context-param配置文件中的bean.它和Struts整合的时候也是这么做的!!