SpringMVC4 + Spring + MyBatis3

本文使用最新版本(4.1.5)的springmvc+spring+mybatis,采用最间的配置方式来进行搭建。

1. web.xml

我们知道springmvc是基于Servlet: DispatcherServlet来处理分发请求的,所以我们需要先在web.xml文件中配置DispatcherServlet,而Spring的启动则是使用了监听器,所以需要配置spring的监听器:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
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_2_5.xsd">
<display-name>sp</display-name> <servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/applicationContext.xml</param-value>
</context-param> </web-app>

servlet下面的init-param中的指定了springmvc的dispatcherServlet的配置文件:config/spring-mvc.xml,所有springmvc相关的都在该文件中进行配置。在DispatcherServlet(其父类)中使用:getServletConfig().getInitParameter("paramName");  可以访问到init-param中指定的参数,从而可以读取到config/spring-mvc.xml文件。load-on-startup值为1指定了dispatcherServlet随servlet容器启动。

ContextLoaderListener是spring监听servlet容器的启动的,在servlet容器启动时,就初始化bean工厂,对bean进行初始化等等操作。context-param指定了spring的配置文件config/applicationContext.xml,可以使用: getServletContext().getInitParameter("paraName"); 读取到值。

注意:init-param 和 context-param 的区别,从名字上就可以看得出,后者是相对于整个web应用的,而前者是针对单个servlet的。

2. springmvc.xml

下面我们看一下springmvc.xml该如何配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <mvc:annotation-driven />
<context:component-scan base-package="net.aazj.controller" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
// ... ...
</beans>

启用注解驱动来扫描controller,并指定control的包路径,还有指定了视图解析器,so easy。

3. applicationContext.xml

spring中相关bean扫描,事物的配置,以及和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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="net.aazj.service" />
<!-- 引入属性文件 -->
<context:property-placeholder location="classpath:config/db.properties" /> <!-- 配置数据源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" />
</bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:config/mybatis-config.xml" />
<property name="mapperLocations" value="classpath*:config/mappers/**/*.xml" />
</bean> <!-- Transaction manager for a single JDBC DataSource -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <!-- 使用annotation定义事务 -->
<tx:annotation-driven transaction-manager="transactionManager" /> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="net.aazj.mapper" />
</bean>
</beans>

同样相关service bean也使用基于注解的扫描方式:context:component-scan,事务也使用注解来驱动:tx:annotation-driven,所以需要在serviceImpl相关类上和方法上使用@Transanctional注解类配置事物。

sqlSessionFactory的配置相当重要,configLocation指定了mybatis的配置文件,如果需要在mybatis配置文件中配置比如<settings>, <typeAliases>, <mappers>则,需要在这里指定,如果不需要就没有必要指定值了。mapperLocations指定了mapper接口映射sql语句的xml文件的位置。MapperScannerConfigurer指定了mapper接口所在的包路径。

4. mybatis-config.xml

spring和mybatis的接口,其实可以不需要mybatis-config.xml文件的存在,只有在需要配置<settings>, <typeAliases>, <mappers>(其实mapper也一并也是在applicationContext.xml中进行配置)才需要mybatis-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> <settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
<typeAliases>
<package name="net.aazj.pojo"/>
</typeAliases>
</configuration>

<settings>指定了数据库操作相关的设置,typeAliases指定了可以给数据库表对应的类所在的包路径,可以在sql的xml使用它们的别名:

package net.aazj.pojo;

import org.apache.ibatis.type.Alias;

@Alias("User")
public class User { private Integer id; private String name; // ... ... }

@Alias("User")注解了该pojo的别名,所以可以在xml文件中使用别名 User 来代替:net.aazj.pojo.User

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.aazj.mapper.UserMapper">
<cache /> <select id="getUser" resultType="User">
select * from user where id = #{id}
</select> <select id="addUser" parameterType="string">
insert into user(name) values(#{name})
</select>
</mapper>

这里 resultType="User" 不需要使用全限定类名。<cache />启用了基于namespace="net.aazj.mapper.UserMapper"的全局缓存。

5. generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration>
<classPathEntry location="D:\java_libs\repository\mysql\mysql-connector-java\5.1.35\mysql-connector-java-5.1.35.jar" /> <context id="MySQLTables" targetRuntime="MyBatis3"> <jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/sy"
userId="root"
password="xxxxx">
</jdbcConnection> <javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver> <javaModelGenerator targetPackage="net.aazj.pojo" targetProject="sp\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator> <sqlMapGenerator targetPackage="config.mappers" targetProject="sp\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="net.aazj.mapper" targetProject="sp\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator> <table schema="sy" tableName="tbug" domainObjectName="Bug" >
<property name="useActualColumnNames" value="false"/>
<generatedKey column="id" sqlStatement="mysql" identity="true" />
<!--
<columnOverride column="DATE_FIELD" property="startDate" />
<ignoreColumn column="FRED" />
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
-->
</table>
<table schema="sy" tableName="user" domainObjectName="User" >
<property name="useActualColumnNames" value="false"/>
<generatedKey column="id" sqlStatement="mysql" identity="true" />
</table> </context>
</generatorConfiguration>

上面是Mybatis generator的配置文件:

1)classPathEntry  指定驱动位置;

2)jdbcConnection 指定数据库连接信息;

3)javaModelGenerator 指定生成的pojo类的位置;

4)sqlMapGenerator 指定指定生成的sql xml文件的位置;

5)javaClientGenerator 指定 mapper 接口的位置;

6)table 指定将数据库中哪些表进行处理;<generatedKey column="id" sqlStatement="mysql" identity="true" /> 用于指定主键;

 

SpringMVC4 + Spring + MyBatis3的更多相关文章

  1. SpringMVC4 + Spring + MyBatis3 基于注解的最简配置

    本文使用最新版本(4.1.5)的springmvc+spring+mybatis,采用最间的配置方式来进行搭建. 1. web.xml 我们知道springmvc是基于Servlet: Dispatc ...

  2. spring4.1+springmvc4.1+mybatis3.2.8+spring-security3.2.5集成环境建设

    在最近使用的项目ssi+spring-security 结构体.建立你自己的家,这是什么环境. 只有记录的目的. 项目结构: 类文件:                                  ...

  3. SpringMVC4+MyBatis3+SQLServer 2014 整合(包括增删改查分页)

    前言 说起整合自然离开ssm,我本身并不太喜欢ORM,尤其是MyBatis,把SQL语句写在xml里,尤其是大SQL,可读性不高,出错也不容易排查. 开发环境 idea2016.SpringMVC4. ...

  4. SpringMVC4+MyBatis+SQL Server2014+druid 监控SQL运行情况

    前言 在基于SpringMVC+MyBatis的开发过程中,我们希望能看到自己手写SQL的执行情况,在开发阶段我们可以配置log4j在控制台里基于debug模式查看,那么上线后,在生产声我们想查看SQ ...

  5. SpringMVC4+MyBatis+SQL Server2014实现读写分离

    前言 基于mybatis的AbstractRoutingDataSource和Interceptor用拦截器的方式实现读写分离,根据MappedStatement的boundsql,查询sql的sel ...

  6. 【Spring实战】----开篇(包含系列目录链接)

    [Spring实战]----开篇(包含系列目录链接) 置顶2016年11月10日 11:12:56 阅读数:3617 终于还是要对Spring进行解剖,接下来Spring实战篇系列会以应用了Sprin ...

  7. SSM手把手整合教程&测试事务

    自打来了博客园就一直在看帖,学到了很多知识,打算开始记录的学习到的知识点 今天我来写个整合SpringMVC4 spring4 mybatis3&测试spring事务的教程,如果有误之处,还请 ...

  8. SSM简单整合教程&测试事务

    自打来了博客园就一直在看帖,学到了很多知识,打算开始记录的学习到的知识点 今天我来写个整合SpringMVC4 spring4 mybatis3&测试spring事务的教程,如果有误之处,还请 ...

  9. 基于Spring4+SpringMVC4+Mybatis3+Hibernate4+Junit4框架构建高性能企业级的部标GPS监控平台

    开发企业级的部标GPS监控平台,投入的开发力量很大,开发周期也很长,选择主流的开发语言以及成熟的开源技术框架来构建基础平台,是最恰当不过的事情,在设计之初就避免掉了技术选型的风险,避免以后在开发过程中 ...

随机推荐

  1. 玩转Web之easyui(一)-----easy ui datagird 分页

    easy ui 中数据表格的分页其实是很简单的,分页是在数据表格可以正常显示数据的基础上进行的,在这里给出servlet的代码,其中selectAll()方法是从数据库中提取所有数据, 分页的一种思路 ...

  2. 在线API大全

    之前整理过几个经常使用api地址,在经常使用在线API集合博文中. 近期浏览网页的时候,又发现一个很完整的api的大全,分享出来,建议大家收藏起来,用的时候方便查询. 经常使用API文档索引http: ...

  3. Handler消息源代码分析

    public static final Looper myLooper() { return (Looper)sThreadLocal.get(); } 首先到Handler运行过程的总结: 1. L ...

  4. POJ 1745 Divisibility (线性dp)

    Divisibility Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 10598   Accepted: 3787 Des ...

  5. C#启动进程之Process

    在程序设计中,我们经常会遇到要从当前的程序跳到另一个程序的设计需求.也就是当前进程创建另一个进程.C#提供了Process使得我们很方便的实现. 1.Process基本属性和方法 Id //进程的Id ...

  6. WCF分布式事务(EF)

    才说分布式事务,首先,了解一下什么是交易. 事务有四个特性:ACID A是Atomicity,原子性.一个事务往往涉及到很多的子操作,原子性则保证这些子操作要么都做,要么都不做,而不至于出现事务的部分 ...

  7. Nginx搭建反向代理服务器过程详解(转)

    一.反向代理 我们都知道,80端口是web服务的默认端口,其他主机访问web服务器也是默认和80端口进行web交互,而一台服务器也只有一个80端口,这是约定俗成的标准. 我们来看下面两个场景: 1.服 ...

  8. windows 10 install oracle 12c error:[ INS-30131 ]

    "[ INS-30131 ] the Initial Setup That Is Required to Run the Installation Program Validation Wa ...

  9. 《Linux Device Drivers》第十四章 Linux 设备型号

    基本介绍 2.6内核设备模型来提供的抽象叙述性描述的一般系统的结构,为了支持各种不同的任务 电源管理和系统关机 用户空间与通信 热插拔设备 设备类型 kobject.kset和子系统 kobject是 ...

  10. linux下一个apache+tomcat负载均衡和集群

    先说一下我的环境 一个ubuntu虚拟机, 一个apache2.2示例 两tomcat1.7示例 1.安装apacheserver sudo apt-get install apache2 假设要重新 ...