手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

SSM(Spring+SpringMVC+Mybatis),目前较为主流的企业级架构方案。标准的MVC设计模式,将整个系统划分为显示层、Controller层、Service层、Dao层四层,使用SpringMVC负责请求的转发和视图管理,Spring实现业务对象管理, MyBatis作为数据对象持久化引擎。

一. 框架详情

  1. Spring 是一个轻量级的Java开发框架,它是为了解决企业应用开发的复杂性而创建的。Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。 简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。

  2. SpringMVC 属于SpringFrameWork的后续产品,分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

  3. MyBatis 是一个基于Java的持久层框架。MyBatis提供的持久层框架包括SQL Maps和Data Access Objects(DAO)它消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java映射成数据库中的记录。

二. 创建Maven项目

  1. Eclipse中用Maven创建项目

    手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

  2. 按默认Next

    手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

  3. 找到maven-archetype-webapp后,点击next

    手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

  4. 填写相应的信息,GroupID是项目组织唯一的标识符,实际对应JAVA的包的结构。ArtifactID就是项目的唯一的标识符,实际对应项目的名称,就是项目根目录的名称。Package填了默认给你建一个包,不写也可以。

    手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

  5. 刚建好的目录如下

    手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

  6. Maven规定必须添加以下Source Folder:
    src/main/resources
    src/main/java
    src/test/resources
    src/test/java
    在这步之前最好先项目上右键选择properties,然后点击java build path,在Librarys下,编辑JRE System Library,选择workspace default jre。

    手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

  7. 分别修改输出路径为,对应关系如下:

    手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

  8. 将项目转换成Dynamic Web Project,在项目上右键Properties,在左侧选择 Project Facets。

    手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

  9. 设置部署时的文件发布路径,删除test的两项,因为test是测试使用,并不需要部署。
    设置将Maven的jar包发布到lib下。Add -> Java Build Path Entries -> Maven Dependencies -> Finish

    手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

    三. Maven引入需要的JAR包

    1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    3. <modelVersion>4.0.0</modelVersion>
    4. <groupId>com.yingjun.test</groupId>
    5. <artifactId>TradingState</artifactId>
    6. <packaging>war</packaging>
    7. <version>2.0.1</version>
    8. <properties>
    9. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    10. <maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
    11. <spring.version>3.2.9.RELEASE</spring.version>
    12. <mybatis.version>3.1.1</mybatis.version>
    13. <mybatisspring.version>1.1.1</mybatisspring.version>
    14. </properties>
    15. <dependencies>
    16. <dependency>
    17. <groupId>org.springframework</groupId>
    18. <artifactId>spring-core</artifactId>
    19. <version>${spring.version}</version>
    20. </dependency>
    21. <dependency>
    22. <groupId>org.springframework</groupId>
    23. <artifactId>spring-webmvc</artifactId>
    24. <version>${spring.version}</version>
    25. </dependency>
    26. <dependency>
    27. <groupId>org.springframework</groupId>
    28. <artifactId>spring-test</artifactId>
    29. <version>${spring.version}</version>
    30. </dependency>
    31. <dependency>
    32. <groupId>org.mybatis</groupId>
    33. <artifactId>mybatis</artifactId>
    34. <version>${mybatis.version}</version>
    35. </dependency>
    36. <dependency>
    37. <groupId>org.mybatis</groupId>
    38. <artifactId>mybatis-spring</artifactId>
    39. <version>${mybatisspring.version}</version>
    40. </dependency>
    41. <dependency>
    42. <groupId>mysql</groupId>
    43. <artifactId>mysql-connector-java</artifactId>
    44. <version>5.1.34</version>
    45. </dependency>
    46. <dependency>
    47. <groupId>junit</groupId>
    48. <artifactId>junit</artifactId>
    49. <version>4.11</version>
    50. <scope>test</scope>
    51. </dependency>
    52. <dependency>
    53. <groupId>c3p0</groupId>
    54. <artifactId>c3p0</artifactId>
    55. <version>0.9.1.2</version>
    56. </dependency>
    57. <dependency>
    58. <groupId>org.aspectj</groupId>
    59. <artifactId>aspectjweaver</artifactId>
    60. <version>1.8.1</version>
    61. </dependency>
    62. <dependency>
    63. <groupId>javax.servlet</groupId>
    64. <artifactId>jstl</artifactId>
    65. <version>1.2</version>
    66. </dependency>
    67. <dependency>
    68. <groupId>javax.servlet</groupId>
    69. <artifactId>servlet-api</artifactId>
    70. <version>3.0</version>
    71. <scope>provided</scope>
    72. </dependency>
    73. <dependency>
    74. <groupId>javax.servlet.jsp</groupId>
    75. <artifactId>jsp-api</artifactId>
    76. <version>2.2</version>
    77. <scope>provided</scope>
    78. </dependency>
    79. <dependency>
    80. <groupId>commons-fileupload</groupId>
    81. <artifactId>commons-fileupload</artifactId>
    82. <version>1.3.1</version>
    83. </dependency>
    84. <dependency>
    85. <groupId>commons-lang</groupId>
    86. <artifactId>commons-lang</artifactId>
    87. <version>2.6</version>
    88. </dependency>
    89. <dependency>
    90. <groupId>commons-codec</groupId>
    91. <artifactId>commons-codec</artifactId>
    92. <version>1.9</version>
    93. </dependency>
    94. <dependency>
    95. <groupId>org.apache.httpcomponents</groupId>
    96. <artifactId>httpclient</artifactId>
    97. <version>4.5</version>
    98. </dependency>
    99. <dependency>
    100. <groupId>org.slf4j</groupId>
    101. <artifactId>slf4j-api</artifactId>
    102. <version>1.7.10</version>
    103. </dependency>
    104. <dependency>
    105. <groupId>org.slf4j</groupId>
    106. <artifactId>slf4j-log4j12</artifactId>
    107. <version>1.7.10</version>
    108. </dependency>
    109. <dependency>
    110. <groupId>log4j</groupId>
    111. <artifactId>log4j</artifactId>
    112. <version>1.2.17</version>
    113. </dependency>
    114. <dependency>
    115. <groupId>com.alibaba</groupId>
    116. <artifactId>fastjson</artifactId>
    117. <version>1.1.41</version>
    118. </dependency>
    119. <dependency>
    120. <groupId>org.codehaus.jackson</groupId>
    121. <artifactId>jackson-mapper-asl</artifactId>
    122. <version>1.9.13</version>
    123. </dependency>
    124. </dependencies>
    125. <build>
    126. <plugins>
    127. <plugin>
    128. <artifactId>maven-compiler-plugin</artifactId>
    129. <version>2.3.2</version>
    130. <configuration>
    131. <source>1.7</source>
    132. <target>1.7</target>
    133. </configuration>
    134. </plugin>
    135. <plugin>
    136. <artifactId>maven-war-plugin</artifactId>
    137. <version>2.2</version>
    138. <configuration>
    139. <version>3.0</version>
    140. <failOnMissingWebXml>false</failOnMissingWebXml>
    141. </configuration>
    142. </plugin>
    143. </plugins>
    144. <finalName>${project.artifactId}_${project.version}_${maven.build.timestamp}</finalName>
    145. </build>
    146. </project>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yingjun.test</groupId>
    <artifactId>TradingState</artifactId>
    <packaging>war</packaging>
    <version>2.0.1</version> <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
    <spring.version>3.2.9.RELEASE</spring.version>
    <mybatis.version>3.1.1</mybatis.version>
    <mybatisspring.version>1.1.1</mybatisspring.version>
    </properties> <dependencies>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
    </dependency>
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>${mybatisspring.version}</version>
    </dependency>
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.34</version>
    </dependency>
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
    </dependency>
    <dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
    </dependency>
    <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.1</version>
    </dependency>
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
    </dependency>
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>3.0</version>
    <scope>provided</scope>
    </dependency>
    <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2</version>
    <scope>provided</scope>
    </dependency>
    <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
    </dependency>
    <dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
    </dependency>
    <dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
    </dependency>
    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5</version>
    </dependency>
    <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.10</version>
    </dependency>
    <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.10</version>
    </dependency>
    <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
    </dependency>
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.1.41</version>
    </dependency>
    <dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
    </dependency>
    </dependencies> <build>
    <plugins>
    <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
    <source>1.7</source>
    <target>1.7</target>
    </configuration>
    </plugin>
    <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.2</version>
    <configuration>
    <version>3.0</version>
    <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
    </plugin>
    </plugins>
    <finalName>${project.artifactId}_${project.version}_${maven.build.timestamp}</finalName>
    </build>
    </project>

    四. 相关配置文件配置,整合SSM框架

    web.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
    4. xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    5. version="2.4">
    6. <!-- 配置 Spring -->
    7. <context-param>
    8. <param-name>contextConfigLocation</param-name>
    9. <param-value>classpath:spring.xml</param-value>
    10. </context-param>
    11. <listener>
    12. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    13. </listener>
    14. <!-- 防止Spring内存溢出监听器 -->
    15. <listener>
    16. <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    17. </listener>
    18. <!-- 配置springmvc -->
    19. <servlet>
    20. <servlet-name>springMVC</servlet-name>
    21. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    22. <init-param>
    23. <param-name>contextConfigLocation</param-name>
    24. <param-value>classpath:spring-mvc.xml</param-value>
    25. </init-param>
    26. <load-on-startup></load-on-startup>
    27. </servlet>
    28. <servlet-mapping>
    29. <servlet-name>springMVC</servlet-name>
    30. <url-pattern>/</url-pattern>
    31. </servlet-mapping>
    32. <!-- 字符集过滤器 -->
    33. <filter>
    34. <filter-name>encodingFilter</filter-name>
    35. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    36. <init-param>
    37. <param-name>encoding</param-name>
    38. <param-value>UTF-</param-value>
    39. </init-param>
    40. <init-param>
    41. <param-name>forceEncoding</param-name>
    42. <param-value>true</param-value>
    43. </init-param>
    44. </filter>
    45. <filter-mapping>
    46. <filter-name>encodingFilter</filter-name>
    47. <url-pattern>/*</url-pattern>
    48. </filter-mapping>
    49. </web-app>
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4"> <!-- 配置 Spring -->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
    </context-param>
    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 防止Spring内存溢出监听器 -->
    <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener> <!-- 配置springmvc -->
    <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping> <!-- 字符集过滤器 -->
    <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
    <param-name>forceEncoding</param-name>
    <param-value>true</param-value>
    </init-param>
    </filter>
    <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping> </web-app>

    spring.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans
    7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    8. http://www.springframework.org/schema/mvc
    9. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    10. http://www.springframework.org/schema/context
    11. http://www.springframework.org/schema/context/spring-context-3.0.xsd
    12. http://www.springframework.org/schema/aop
    13. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    14. http://www.springframework.org/schema/tx
    15. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
    16. <!-- 扫描service、dao组件 -->
    17. <context:component-scan base-package="com.yingjun.test" />
    18. <!-- 分解配置 jdbc.properites -->
    19. <context:property-placeholder location="classpath:jdbc.properties" />
    20. <!-- 数据源c3p0 -->
    21. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    22. <property name="driverClass" value="${jdbc.driverClassName}" />
    23. <property name="jdbcUrl" value="${jdbc.url}" />
    24. <property name="user" value="${jdbc.username}" />
    25. <property name="password" value="${jdbc.password}" />
    26. <property name="maxPoolSize" value="${c3p0.pool.size.max}" />
    27. <property name="minPoolSize" value="${c3p0.pool.size.min}" />
    28. <property name="initialPoolSize" value="${c3p0.pool.size.ini}" />
    29. <property name="acquireIncrement" value="${c3p0.pool.size.increment}" />
    30. </bean>
    31. <!-- sessionFactory 将spring和mybatis整合 -->
    32. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    33. <property name="dataSource" ref="dataSource" />
    34. <property name="configLocation" value="classpath:spring-mybatis.xml" />
    35. <property name="mapperLocations" value="classpath*:com/yingjun/test/mapping/**/*.xml" />
    36. </bean>
    37. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    38. <property name="basePackage" value="com,yingjun.test.dao" />
    39. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    40. </bean>
    41. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    42. <property name="dataSource" ref="dataSource" />
    43. </bean>
    44. <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
    45. <tx:attributes>
    46. <tx:method name="add*" propagation="REQUIRED" />
    47. <tx:method name="append*" propagation="REQUIRED" />
    48. <tx:method name="insert*" propagation="REQUIRED" />
    49. <tx:method name="save*" propagation="REQUIRED" />
    50. <tx:method name="update*" propagation="REQUIRED" />
    51. <tx:method name="modify*" propagation="REQUIRED" />
    52. <tx:method name="edit*" propagation="REQUIRED" />
    53. <tx:method name="delete*" propagation="REQUIRED" />
    54. <tx:method name="remove*" propagation="REQUIRED" />
    55. <tx:method name="repair" propagation="REQUIRED" />
    56. <tx:method name="delAndRepair" propagation="REQUIRED" />
    57. <tx:method name="get*" propagation="SUPPORTS" />
    58. <tx:method name="find*" propagation="SUPPORTS" />
    59. <tx:method name="load*" propagation="SUPPORTS" />
    60. <tx:method name="search*" propagation="SUPPORTS" />
    61. <tx:method name="datagrid*" propagation="SUPPORTS" />
    62. <tx:method name="*" propagation="SUPPORTS" />
    63. </tx:attributes>
    64. </tx:advice>
    65. <aop:config>
    66. <aop:pointcut id="transactionPointcut" expression="execution(* com.yingjun.test.service..*Impl.*(..))" />
    67. <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
    68. </aop:config>
    69. </beans>
    <?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "> <!-- 扫描service、dao组件 -->
    <context:component-scan base-package="com.yingjun.test" />
    <!-- 分解配置 jdbc.properites -->
    <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 数据源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}" />
    <property name="maxPoolSize" value="${c3p0.pool.size.max}" />
    <property name="minPoolSize" value="${c3p0.pool.size.min}" />
    <property name="initialPoolSize" value="${c3p0.pool.size.ini}" />
    <property name="acquireIncrement" value="${c3p0.pool.size.increment}" />
    </bean> <!-- sessionFactory 将spring和mybatis整合 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:spring-mybatis.xml" />
    <property name="mapperLocations" value="classpath*:com/yingjun/test/mapping/**/*.xml" />
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com,yingjun.test.dao" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
    </bean>
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
    <tx:attributes>
    <tx:method name="add*" propagation="REQUIRED" />
    <tx:method name="append*" propagation="REQUIRED" />
    <tx:method name="insert*" propagation="REQUIRED" />
    <tx:method name="save*" propagation="REQUIRED" />
    <tx:method name="update*" propagation="REQUIRED" />
    <tx:method name="modify*" propagation="REQUIRED" />
    <tx:method name="edit*" propagation="REQUIRED" />
    <tx:method name="delete*" propagation="REQUIRED" />
    <tx:method name="remove*" propagation="REQUIRED" />
    <tx:method name="repair" propagation="REQUIRED" />
    <tx:method name="delAndRepair" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" />
    <tx:method name="find*" propagation="SUPPORTS" />
    <tx:method name="load*" propagation="SUPPORTS" />
    <tx:method name="search*" propagation="SUPPORTS" />
    <tx:method name="datagrid*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" />
    </tx:attributes>
    </tx:advice>
    <aop:config>
    <aop:pointcut id="transactionPointcut" expression="execution(* com.yingjun.test.service..*Impl.*(..))" />
    <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
    </aop:config>
    </beans>

    为了代替手工使用 SqlSessionDaoSupport 或 SqlSessionTemplate 编写数据访问对象 (DAO)的代码,MyBatis-Spring 提供了一个动态代理的实现:MapperFactoryBean。这个类 可以让你直接注入数据映射器接口到你的 service 层 bean 中。当使用映射器时,你仅仅如调 用你的 DAO 一样调用它们就可以了,但是你不需要编写任何 DAO 实现的代码,因为 MyBatis-Spring 将会为你创建代理。

    spring-mybatis.xml

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    3. <configuration>
    4. <!-- 暂时不需要其他配置-->
    5. </configuration>
    <?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>
    <!-- 暂时不需要其他配置-->
    </configuration>

    spring-mvc.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:mvc="http://www.springframework.org/schema/mvc"
    6. xsi:schemaLocation="
    7. http://www.springframework.org/schema/beans
    8. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    9. http://www.springframework.org/schema/context
    10. http://www.springframework.org/schema/context/spring-context-3.0.xsd
    11. http://www.springframework.org/schema/mvc
    12. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    13. <!-- 默认的注解映射的支持 -->
    14. <mvc:annotation-driven />
    15. <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    16. <context:component-scan base-package="com.yingjun.test.controller" />
    17. <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
    18. <bean id="mappingJacksonHttpMessageConverter"
    19. class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    20. <property name="supportedMediaTypes">
    21. <list>
    22. <value>text/html;charset=UTF-</value>
    23. </list>
    24. </property>
    25. </bean>
    26. <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
    27. <bean
    28. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    29. <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
    30. <property name="prefix" value="/WEB-INF/jsp/" />
    31. <property name="suffix" value=".jsp" />
    32. </bean>
    33. <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
    34. <bean id="multipartResolver"
    35. class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    36. <!-- 默认编码 -->
    37. <property name="defaultEncoding" value="utf-8" />
    38. <!-- 文件大小最大值 -->
    39. <property name="maxUploadSize" value="10485760000" />
    40. <!-- 内存中的最大值 -->
    41. <property name="maxInMemorySize" value="40960" />
    42. </bean>
    43. </beans>
    <?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: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-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 默认的注解映射的支持 -->
    <mvc:annotation-driven /> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    <context:component-scan base-package="com.yingjun.test.controller" /> <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
    <bean id="mappingJacksonHttpMessageConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes">
    <list>
    <value>text/html;charset=UTF-8</value>
    </list>
    </property>
    </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
    <bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
    </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
    <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 默认编码 -->
    <property name="defaultEncoding" value="utf-8" />
    <!-- 文件大小最大值 -->
    <property name="maxUploadSize" value="10485760000" />
    <!-- 内存中的最大值 -->
    <property name="maxInMemorySize" value="40960" />
    </bean> </beans>

    log4j.properties

    1. jdbc.driverClassName=com.mysql.jdbc.Driver
    2. jdbc.url=jdbc:mysql://192.168.1.194:3306/test?useUnicode=true&characterEncoding=UTF-8
    3. jdbc.username=root
    4. jdbc.password=root
    5. c3p0.pool.size.max=20
    6. c3p0.pool.size.min=5
    7. c3p0.pool.size.ini=3
    8. c3p0.pool.size.increment=2
    jdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://192.168.1.194:3306/test?useUnicode=true&characterEncoding=UTF-8
    jdbc.username=root
    jdbc.password=root c3p0.pool.size.max=20
    c3p0.pool.size.min=5
    c3p0.pool.size.ini=3
    c3p0.pool.size.increment=2

    jdbc.properties

    1. log4j.rootLogger=info, console, debug, app, error
    2. ###Console ###
    3. log4j.appender.console = org.apache.log4j.ConsoleAppender
    4. log4j.appender.console.Target = System.out
    5. log4j.appender.console.layout = org.apache.log4j.PatternLayout
    6. log4j.appender.console.layout.ConversionPattern = %d %p[%C:%L]- %m%n
    7. ### debug ###
    8. log4j.appender.debug = org.apache.log4j.DailyRollingFileAppender
    9. log4j.appender.debug.File = log/debug.log
    10. log4j.appender.debug.Append = true
    11. log4j.appender.debug.Threshold = DEBUG
    12. log4j.appender.debug.DatePattern='.'yyyy-MM-dd
    13. log4j.appender.debug.layout = org.apache.log4j.PatternLayout
    14. log4j.appender.debug.layout.ConversionPattern = %d %p[%c:%L] - %m%n
    15. ### app ###
    16. log4j.appender.app = org.apache.log4j.DailyRollingFileAppender
    17. log4j.appender.app.File = log/app.log
    18. log4j.appender.app.Append = true
    19. log4j.appender.app.Threshold = INFO
    20. log4j.appender.app.DatePattern='.'yyyy-MM-dd
    21. log4j.appender.app.layout = org.apache.log4j.PatternLayout
    22. log4j.appender.app.layout.ConversionPattern = %d %p[%c:%L] - %m%n
    23. ### Error ###
    24. log4j.appender.error = org.apache.log4j.DailyRollingFileAppender
    25. log4j.appender.error.File = log/error.log
    26. log4j.appender.error.Append = true
    27. log4j.appender.error.Threshold = ERROR
    28. log4j.appender.error.DatePattern='.'yyyy-MM-dd
    29. log4j.appender.error.layout = org.apache.log4j.PatternLayout
    30. log4j.appender.error.layout.ConversionPattern =%d %p[%c:%L] - %m%n
    log4j.rootLogger=info, console, debug, app, error
    
    ###Console ###
    log4j.appender.console = org.apache.log4j.ConsoleAppender
    log4j.appender.console.Target = System.out
    log4j.appender.console.layout = org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern = %d %p[%C:%L]- %m%n ### debug ###
    log4j.appender.debug = org.apache.log4j.DailyRollingFileAppender
    log4j.appender.debug.File = log/debug.log
    log4j.appender.debug.Append = true
    log4j.appender.debug.Threshold = DEBUG
    log4j.appender.debug.DatePattern='.'yyyy-MM-dd
    log4j.appender.debug.layout = org.apache.log4j.PatternLayout
    log4j.appender.debug.layout.ConversionPattern = %d %p[%c:%L] - %m%n ### app ###
    log4j.appender.app = org.apache.log4j.DailyRollingFileAppender
    log4j.appender.app.File = log/app.log
    log4j.appender.app.Append = true
    log4j.appender.app.Threshold = INFO
    log4j.appender.app.DatePattern='.'yyyy-MM-dd
    log4j.appender.app.layout = org.apache.log4j.PatternLayout
    log4j.appender.app.layout.ConversionPattern = %d %p[%c:%L] - %m%n ### Error ###
    log4j.appender.error = org.apache.log4j.DailyRollingFileAppender
    log4j.appender.error.File = log/error.log
    log4j.appender.error.Append = true
    log4j.appender.error.Threshold = ERROR
    log4j.appender.error.DatePattern='.'yyyy-MM-dd
    log4j.appender.error.layout = org.apache.log4j.PatternLayout
    log4j.appender.error.layout.ConversionPattern =%d %p[%c:%L] - %m%n

    五. 利用MyBatis Generator自动创建实体类、映射文件以及DAO接口

    MyBatis属于一种半自动的ORM框架,所以主要的工作就是配置Mapping映射文件,但是由于手写映射文件很容易出错,所以可利用MyBatis生成器自动生成实体类、DAO接口和Mapping映射文件。这样可以省去很多的功夫,将生成的代码copy到项目工程中即可。
    生成代码需要的文件和jar并建立如下目录结构:

    手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

    在generatorl.xml中配置相关的数据库连接,已经数据库表:

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <!DOCTYPE generatorConfiguration
    3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
    4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    5. <generatorConfiguration>
    6. <!-- 数据库驱动 -->
    7. <classPathEntry location="mysql-connector-java-5.1.34.jar" />
    8. <context id="DB2Tables" targetRuntime="MyBatis3">
    9. <commentGenerator>
    10. <property name="suppressDate" value="true" />
    11. <!-- 是否去除自动生成的注释 true:是 : false:否 -->
    12. <property name="suppressAllComments" value="true" />
    13. </commentGenerator>
    14. <!--数据库链接URL,用户名、密码 -->
    15. <jdbcConnection driverClass="com.mysql.jdbc.Driver"
    16. connectionURL="jdbc:mysql://192.168.1.194:3306/noc"
    17. userId="root" password="root">
    18. </jdbcConnection>
    19. <javaTypeResolver>
    20. <property name="forceBigDecimals" value="false" />
    21. </javaTypeResolver>
    22. <!-- 生成模型的包名和位置 -->
    23. <javaModelGenerator targetPackage="com.yingjun.test.model"
    24. targetProject="src">
    25. <property name="enableSubPackages" value="true" />
    26. <property name="trimStrings" value="true" />
    27. </javaModelGenerator>
    28. <!-- 生成映射文件的包名和位置 -->
    29. <sqlMapGenerator targetPackage="com.yingjun.test.mapping"
    30. targetProject="src">
    31. <property name="enableSubPackages" value="true" />
    32. </sqlMapGenerator>
    33. <!-- 生成DAO的包名和位置 -->
    34. <javaClientGenerator type="XMLMAPPER" targetPackage="com.yingjun.test.dao"
    35. targetProject="src">
    36. <property name="enableSubPackages" value="true" />
    37. </javaClientGenerator>
    38. <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名 -->
    39. <table tableName="other_list" domainObjectName="OtherList"
    40. enableCountByExample="fasle" enableUpdateByExample="false"
    41. enableDeleteByExample="false" enableSelectByExample="false"
    42. selectByExampleQueryId="false" >
    43. </table>
    44. </context>
    45. </generatorConfiguration>
    <?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="mysql-connector-java-5.1.34.jar" />
    <context id="DB2Tables" targetRuntime="MyBatis3">
    <commentGenerator>
    <property name="suppressDate" value="true" />
    <!-- 是否去除自动生成的注释 true:是 : false:否 -->
    <property name="suppressAllComments" value="true" />
    </commentGenerator>
    <!--数据库链接URL,用户名、密码 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
    connectionURL="jdbc:mysql://192.168.1.194:3306/noc"
    userId="root" password="root">
    </jdbcConnection>
    <javaTypeResolver>
    <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>
    <!-- 生成模型的包名和位置 -->
    <javaModelGenerator targetPackage="com.yingjun.test.model"
    targetProject="src">
    <property name="enableSubPackages" value="true" />
    <property name="trimStrings" value="true" />
    </javaModelGenerator>
    <!-- 生成映射文件的包名和位置 -->
    <sqlMapGenerator targetPackage="com.yingjun.test.mapping"
    targetProject="src">
    <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>
    <!-- 生成DAO的包名和位置 -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.yingjun.test.dao"
    targetProject="src">
    <property name="enableSubPackages" value="true" />
    </javaClientGenerator>
    <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名 -->
    <table tableName="other_list" domainObjectName="OtherList"
    enableCountByExample="fasle" enableUpdateByExample="false"
    enableDeleteByExample="false" enableSelectByExample="false"
    selectByExampleQueryId="false" >
    </table>
    </context>
    </generatorConfiguration>

    打开CMD窗口 进入该目录结构,输入命令行:

    java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite

    运行完成后会生成相应的dao mapper 和model,是不是很爽。

    六. 建立Service层以及conrorller层

    1. package com.yingjun.test.service;
    2. public interface OtherServiceI {
    3. public String getOterList();
    4. }
    package com.yingjun.test.service;
    
    public interface OtherServiceI {
    
    	public String getOterList();
    
    }
    
    1. package com.yingjun.test.service;
    2. import java.util.ArrayList;
    3. import java.util.Arrays;
    4. import java.util.HashSet;
    5. import java.util.List;
    6. import java.util.Map;
    7. import java.util.Set;
    8. import org.springframework.beans.factory.annotation.Autowired;
    9. import org.springframework.stereotype.Service;
    10. import com.alibaba.fastjson.JSON;
    11. import com.alibaba.fastjson.serializer.SerializerFeature;
    12. import com.yingjun.test.dao.OtherListMapper;
    13. import com.yingjun.test.model.OtherList;
    14. import com.yingjun.test.model.OtherListDomain;
    15. @Service
    16. public class OtherServiceImpl implements OtherServiceI {
    17. @Autowired
    18. private OtherListMapper otherListMapper;
    19. @Override
    20. public String getOterList() {
    21. Set<String> set=new HashSet<String>();
    22. List<OtherList> list=otherListMapper.selectAll();
    23. List<OtherListDomain> jsonList=new ArrayList<OtherListDomain>();
    24. for(OtherList other:list){
    25. String title=other.getTitle();
    26. if(set.contains(title)){
    27. continue;
    28. }else{
    29. List<OtherList> t_list=new ArrayList<OtherList>();
    30. for(OtherList data:list){
    31. if(title.equals(data.getTitle())){
    32. t_list.add(data);
    33. }
    34. }
    35. OtherListDomain domain=new OtherListDomain();
    36. domain.setTitle(title);
    37. domain.setItems(t_list);
    38. jsonList.add(domain);
    39. set.add(other.getTitle());
    40. }
    41. }
    42. return JSON.toJSONString(jsonList, SerializerFeature.WriteMapNullValue);
    43. }
    44. }
    package com.yingjun.test.service;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Map;
    import java.util.Set; import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.serializer.SerializerFeature;
    import com.yingjun.test.dao.OtherListMapper;
    import com.yingjun.test.model.OtherList;
    import com.yingjun.test.model.OtherListDomain;
    @Service
    public class OtherServiceImpl implements OtherServiceI { @Autowired
    private OtherListMapper otherListMapper; @Override
    public String getOterList() {
    Set<String> set=new HashSet<String>();
    List<OtherList> list=otherListMapper.selectAll();
    List<OtherListDomain> jsonList=new ArrayList<OtherListDomain>();
    for(OtherList other:list){
    String title=other.getTitle();
    if(set.contains(title)){
    continue;
    }else{
    List<OtherList> t_list=new ArrayList<OtherList>();
    for(OtherList data:list){
    if(title.equals(data.getTitle())){
    t_list.add(data);
    }
    }
    OtherListDomain domain=new OtherListDomain();
    domain.setTitle(title);
    domain.setItems(t_list);
    jsonList.add(domain);
    set.add(other.getTitle());
    }
    }
    return JSON.toJSONString(jsonList, SerializerFeature.WriteMapNullValue);
    } }
    1. package com.yingjun.test.controller;
    2. import org.springframework.beans.factory.annotation.Autowired;
    3. import org.springframework.stereotype.Controller;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. import org.springframework.web.bind.annotation.ResponseBody;
    6. import com.alibaba.fastjson.JSON;
    7. import com.yingjun.test.service.OtherServiceI;
    8. import com.yingjun.test.service.StockStatusServiceI;
    9. @Controller
    10. @RequestMapping(value = "/")
    11. public class TSSController {
    12. @Autowired
    13. private OtherServiceI otherService;
    14. @RequestMapping(value="/getOtherList",produces="text/html;charset=UTF-8" )
    15. @ResponseBody
    16. private String getOtherList(){
    17. String json=otherService.getOterList();
    18. return json;
    19. }
    20. }
    package com.yingjun.test.controller;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON;
    import com.yingjun.test.service.OtherServiceI;
    import com.yingjun.test.service.StockStatusServiceI;
    @Controller
    @RequestMapping(value = "/")
    public class TSSController { @Autowired
    private OtherServiceI otherService; @RequestMapping(value="/getOtherList",produces="text/html;charset=UTF-8" )
    @ResponseBody
    private String getOtherList(){
    String json=otherService.getOterList();
    return json;
    }
    }

    七. 建立测试类

    1. import java.util.List;
    2. import org.apache.log4j.LogManager;
    3. import org.apache.log4j.Logger;
    4. import org.junit.Test;
    5. import org.junit.runner.RunWith;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.test.context.ContextConfiguration;
    8. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    9. @RunWith(SpringJUnit4ClassRunner.class)
    10. @ContextConfiguration(locations = {"classpath:spring.xml"})
    11. public class TestMybatis {
    12. @Autowired
    13. private OtherServiceI service;
    14. @Test
    15. public void test() {
    16. String list=service.getOterList();
    17. logger.info(list);
    18. }
    19. }
    import java.util.List;
    
    import org.apache.log4j.LogManager;
    import org.apache.log4j.Logger;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath:spring.xml"})
    public class TestMybatis { @Autowired
    private OtherServiceI service; @Test
    public void test() {
    String list=service.getOterList();
    logger.info(list);
    } }

    八. 通过浏览器进行验证

    http://localhost:8080/TzyjStateService/getOtherList

至此,测试成功,SSM三大框架的整合就完成了,有什么其他需求可以在此基础继续添加。

上一篇:input:text 的value 和 attribute('value') 不是一回事


下一篇:【ASP.NET Web API教程】2.4 创建Web API的帮助页面