Idea SpringMVC+Spring+MyBatis+Maven整合


创建项目

File-New Project

选中左侧的Maven,选中右侧上方的Create from archetype,然后选中下方列表中的webapp,然后点击Next

Idea SpringMVC+Spring+MyBatis+Maven整合_第1张图片


在GroupId和ArtifactId中填入指定内容,点击Next

Idea SpringMVC+Spring+MyBatis+Maven整合_第2张图片

直接点Next

Idea SpringMVC+Spring+MyBatis+Maven整合_第3张图片


输入项目名称,Finish

Idea SpringMVC+Spring+MyBatis+Maven整合_第4张图片


Idea会自动开始下载所依赖的包,等待其完成。


项目结构

Idea SpringMVC+Spring+MyBatis+Maven整合_第5张图片


项目刚建好的时候是没有这些文件的,所以自己手动创建缺少的文件夹(包)

创建完后的项目框架:

Idea SpringMVC+Spring+MyBatis+Maven整合_第6张图片


修改pom.xml导入依赖包插件

依赖包需要如下:

spring framework
aspectj事务
c3p0数据源
servlet/jsp api
junit4
mybatis
mybatis spring整合
mysql driver

jstl


[html]  view plain  copy
 
  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.0modelVersion>  
  4.     <groupId>com.elin4it.ssmgroupId>  
  5.     <artifactId>ssmartifactId>  
  6.     <packaging>warpackaging>  
  7.     <version>1.0-SNAPSHOTversion>  
  8.     <name>ssm Maven Webappname>  
  9.     <url>http://maven.apache.orgurl>  
  10.     <build>  
  11.         <finalName>ssmfinalName>  
  12.         <plugins>  
  13.               
  14.             <plugin>  
  15.                 <groupId>org.mybatis.generatorgroupId>  
  16.                 <artifactId>mybatis-generator-maven-pluginartifactId>  
  17.                 <version>1.3.2version>  
  18.                 <configuration>  
  19.                     <verbose>trueverbose>  
  20.                     <overwrite>trueoverwrite>  
  21.                 configuration>  
  22.             plugin>  
  23.         plugins> 

  24.      
            src/main/java
           
              **/*.properties
              **/*.xml
           

            false
          <
    /resource>
              
  25.     build>  
  26.     <properties>  
  27.         <spring.version>4.1.1.RELEASEspring.version>  
  28.     properties>  
  29.     <dependencies>  
  30.           
  31.         <dependency>  
  32.             <groupId>org.springframeworkgroupId>  
  33.             <artifactId>spring-coreartifactId>  
  34.             <version>${spring.version}version>  
  35.         dependency>  
  36.   
  37.         <dependency>  
  38.             <groupId>org.springframeworkgroupId>  
  39.             <artifactId>spring-webartifactId>  
  40.             <version>${spring.version}version>  
  41.         dependency>  
  42.   
  43.         <dependency>  
  44.             <groupId>org.springframeworkgroupId>  
  45.             <artifactId>spring-oxmartifactId>  
  46.             <version>${spring.version}version>  
  47.         dependency>  
  48.   
  49.         <dependency>  
  50.             <groupId>org.springframeworkgroupId>  
  51.             <artifactId>spring-txartifactId>  
  52.             <version>${spring.version}version>  
  53.         dependency>  
  54.   
  55.         <dependency>  
  56.             <groupId>org.springframeworkgroupId>  
  57.             <artifactId>spring-jdbcartifactId>  
  58.             <version>${spring.version}version>  
  59.         dependency>  
  60.   
  61.         <dependency>  
  62.             <groupId>org.springframeworkgroupId>  
  63.             <artifactId>spring-webmvcartifactId>  
  64.             <version>${spring.version}version>  
  65.         dependency>  
  66.   
  67.         <dependency>  
  68.             <groupId>org.springframeworkgroupId>  
  69.             <artifactId>spring-aopartifactId>  
  70.             <version>${spring.version}version>  
  71.         dependency>  
  72.   
  73.         <dependency>  
  74.             <groupId>org.springframeworkgroupId>  
  75.             <artifactId>spring-context-supportartifactId>  
  76.             <version>${spring.version}version>  
  77.         dependency>  
  78.   
  79.         <dependency>  
  80.             <groupId>org.springframeworkgroupId>  
  81.             <artifactId>spring-testartifactId>  
  82.             <version>${spring.version}version>  
  83.         dependency>  
  84.           
  85.   
  86.           
  87.         <dependency>  
  88.             <groupId>org.aspectjgroupId>  
  89.             <artifactId>aspectjweaverartifactId>  
  90.             <version>1.8.6version>  
  91.         dependency>  
  92.   
  93.         <dependency>  
  94.             <groupId>org.aspectjgroupId>  
  95.             <artifactId>aspectjrtartifactId>  
  96.             <version>1.8.6version>  
  97.         dependency>  
  98.           
  99.   
  100.           
  101.         <dependency>  
  102.             <groupId>com.mchangegroupId>  
  103.             <artifactId>c3p0artifactId>  
  104.             <version>0.9.5.1version>  
  105.         dependency>  
  106.   
  107.           
  108.         <dependency>  
  109.             <groupId>javax.servletgroupId>  
  110.             <artifactId>servlet-apiartifactId>  
  111.             <version>2.5version>  
  112.         dependency>  
  113.   
  114.         <dependency>  
  115.             <groupId>javax.servlet.jspgroupId>  
  116.             <artifactId>jsp-apiartifactId>  
  117.             <version>2.1version>  
  118.             <scope>providedscope>  
  119.         dependency>  
  120.           
  121.   
  122.           
  123.         <dependency>  
  124.             <groupId>junitgroupId>  
  125.             <artifactId>junitartifactId>  
  126.             <version>4.11version>  
  127.             <scope>testscope>  
  128.         dependency>  
  129.   
  130.           
  131.         <dependency>  
  132.             <groupId>org.mybatisgroupId>  
  133.             <artifactId>mybatisartifactId>  
  134.             <version>3.3.0version>  
  135.         dependency>  
  136.           
  137.         <dependency>  
  138.             <groupId>org.mybatisgroupId>  
  139.             <artifactId>mybatis-springartifactId>  
  140.             <version>1.2.3version>  
  141.         dependency>  
  142.   
  143.           
  144.         <dependency>  
  145.             <groupId>mysqlgroupId>  
  146.             <artifactId>mysql-connector-javaartifactId>  
  147.             <version>5.1.6version>  
  148.         dependency>  
  149.   
  150.           
  151.         <dependency>  
  152.             <groupId>jstlgroupId>  
  153.             <artifactId>jstlartifactId>  
  154.             <version>1.2version>  
  155.         dependency>  
  156.   
  157.     dependencies>  
  158. project>  


插件需要用到mybatis的逆向工程


完整的pom.xml代码清单:


使用mybatis逆向工程创建mapper接口和xml文件

user表结构

[sql]  view plain  copy
 
  1. DROP TABLE IF EXISTS `user`;  
  2. /*!40101 SET @saved_cs_client     = @@character_set_client */;  
  3. /*!40101 SET character_set_client = utf8 */;  
  4. CREATE TABLE `user` (  
  5.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  6.   `username` varchar(32) NOT NULL COMMENT '用户名称',  
  7.   `birthday` date DEFAULT NULL COMMENT '生日',  
  8.   `sex` char(1) DEFAULT NULL COMMENT '性别',  
  9.   `address` varchar(256) DEFAULT NULL COMMENT '地址',  
  10.   PRIMARY KEY (`id`)  
  11. ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;  

在main/resources中创建generatorConfig.xml文件

generatorConfig.xml代码清单

[html]  view plain  copy
 
  1. xml version="1.0" encoding="UTF-8"?>  
  2.         PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"  
  3.         "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">  
  4.   
  5. <generatorConfiguration>  
  6.     <classPathEntry location="F:\jar\mysql\mysql-connector-java-5.1.7-bin.jar"/>  
  7.     <context id="testTables" targetRuntime="MyBatis3" >  
  8.         <commentGenerator>  
  9.               
  10.             <property name="suppressAllComments" value="true" />  
  11.         commentGenerator>  
  12.           
  13.           
  14.                           
  15.                           
  16.                           
  17.           
  18.         <jdbcConnection driverClass="com.mysql.jdbc.Driver"  
  19.             connectionURL="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=UTF-8"  
  20.             userId="root"  
  21.             password="">  
  22.         jdbcConnection>  
  23.   
  24.           
  25.         <javaModelGenerator targetPackage="com.elin4it.ssm.pojo"  
  26.                             targetProject="src\main\java">  
  27.               
  28.             <property name="enableSubPackages" value="false" />  
  29.               
  30.             <property name="trimStrings" value="true" />  
  31.         javaModelGenerator>  
  32.           
  33.         <sqlMapGenerator targetPackage="com.elin4it.ssm.mapper"  
  34.                          targetProject="src\main\resources">  
  35.               
  36.             <property name="enableSubPackages" value="false" />  
  37.         sqlMapGenerator>  
  38.           
  39.         <javaClientGenerator type="XMLMAPPER"  
  40.                              targetPackage="com.elin4it.ssm.mapper"  
  41.                              targetProject="src\main\java">  
  42.               
  43.             <property name="enableSubPackages" value="false" />  
  44.         javaClientGenerator>  
  45.           
  46.         <table tableName="user">table>  
  47.   
  48.           
  49.        <context:component-scan base-package="com.elin4it.ssm.controller"/>  
  50.          
  51.        <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  52.               <property name="prefix" value="/WEB-INF/views/"/>  
  53.               <property name="suffix" value=".jsp"/>  
  54.        bean>  
  55.          
  56.        <mvc:annotation-driven>mvc:annotation-driven>  
  57. beans>  

Spring IOC注入和事件控制

在resources/config/spring中创建applicationContext-dao.xml、application-service.xml、applicationContext-transaction.xml文件


applicationContext-dao.xml

[html]  view plain  copy
 
  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"  
  4.        xmlns:context="http://www.springframework.org/schema/context"  
  5.        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">  
  6.   
  7.   
  8.          
  9.        <context:property-placeholder location="classpath:config/db.properties"/>  
  10.   
  11.   
  12.          
  13.        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">  
  14.               <property name="driverClass" value="${jdbc.driver}"/>  
  15.               <property name="jdbcUrl" value="${jdbc.url}"/>  
  16.               <property name="user" value="${jdbc.username}"/>  
  17.               <property name="password" value="${jdbc.password}"/>  
  18.               <property name="maxPoolSize" value="50"/>  
  19.               <property name="minPoolSize" value="2"/>  
  20.               <property name="maxIdleTime" value="60"/>  
  21.        bean>  
  22.   
  23.          
  24.        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">  
  25.               <property name="configLocation" value="classpath:config/mybatis/SqlMapConfig.xml"/>  
  26.               <property name="dataSource" ref="dataSource"/>  
  27.        bean>  
  28.   
  29.          
  30.        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  31.               <property name="basePackage" value="com.elin4it.ssm.mapper"/>  
  32.               <property name="sqlSessionFactoryBeanName" value="sqlSession"/>  
  33.        bean>  
  34.   
  35. beans>  


application-service.xml

[html]  view plain  copy
 
  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"  
  4.        xmlns:context="http://www.springframework.org/schema/context"  
  5.        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">  
  6.          
  7.          
  8.        <context:component-scan base-package="com.elin4it.ssm.service"/>  
  9. beans>  

applicationContext-transaction.xml

[html]  view plain  copy
 
  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:tx="http://www.springframework.org/schema/tx"  
  4.        xmlns:aop="http://www.springframework.org/schema/aop"  
  5.        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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">  
  6.   
  7.   
  8.        <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  9.               <property name="dataSource" ref="dataSource"/>  
  10.        bean>  
  11.   
  12.        <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">  
  13.               <tx:attributes>  
  14.                      <tx:method name="find*" propagation="REQUIRED"/>  
  15.                      <tx:method name="update*" propagation="REQUIRED"/>  
  16.                      <tx:method name="delete*" propagation="REQUIRED"/>  
  17.                      <tx:method name="add*" propagation="REQUIRED"/>  
  18.               tx:attributes>  
  19.        tx:advice>  
  20.   
  21.        <aop:config>  
  22.               <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.elinzhou.ixxs.service.*.*(..))"/>  
  23.        aop:config>  
  24. beans>  

web.xml文件

修改web.xml文件内容

[html]  view plain  copy
 
  1. xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"  
  3.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"  
  5.          version="3.1">  
  6.   
  7.       
  8.     <context-param>  
  9.         <param-name>contextConfigLocationparam-name>  
  10.         <param-value>classpath*:config/spring/applicationContext-*.xmlparam-value>  
  11.   
  12.     context-param>  
  13.       
  14.     <listener>  
  15.         <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>  
  16.     listener>  
  17.   
  18.   
  19.       
  20.     <filter>  
  21.         <filter-name>CharacterEncodingFilterfilter-name>  
  22.         <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>  
  23.         <init-param>  
  24.             <param-name>encodingparam-name>  
  25.             <param-value>utf-8param-value>  
  26.         init-param>  
  27.     filter>  
  28.     <filter-mapping>  
  29.         <filter-name>CharacterEncodingFilterfilter-name>  
  30.         <url-pattern>/*url-pattern>  
  31.     filter-mapping>  
  32.   
  33.       
  34.     <servlet>  
  35.         <servlet-name>dispatcherServletservlet-name>  
  36.         <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>  
  37.         <init-param>  
  38.             <param-name>contextConfigLocationparam-name>  
  39.             <param-value>classpath*:config/spring/springmvc.xmlparam-value>  
  40.         init-param>  
  41.         <load-on-startup>1load-on-startup>  
  42.     servlet>  
  43.   
  44.     <servlet-mapping>  
  45.         <servlet-name>dispatcherServletservlet-name>  
  46.         <url-pattern>/url-pattern>  
  47.     servlet-mapping>  
  48.   
  49. web-app>  

Service接口与实现

创建一个简单的service,只有一个查看所有用户列表的功能

UserService.java

[java]  view plain  copy
 
  1. package com.elin4it.ssm.service;  
  2.   
  3. import com.elin4it.ssm.pojo.User;  
  4.   
  5. import java.util.List;  
  6.   
  7. /** 
  8.  * Created by 烽 on 2015/7/11. 
  9.  */  
  10. public interface UserService {  
  11.   
  12.     /** 
  13.      * 查找所有用户 
  14.      * @return 
  15.      * @throws Exception 
  16.      */  
  17.     List findUser()throws Exception;  
  18. }  

实现类UserServiceImpl.java

[java]  view plain  copy
 
  1. package com.elin4it.ssm.service;  
  2.   
  3. import com.elin4it.ssm.mapper.UserMapper;  
  4. import com.elin4it.ssm.pojo.User;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Service;  
  7.   
  8. import java.util.List;  
  9.   
  10. /** 
  11.  * Created by 烽 on 2015/7/11. 
  12.  */  
  13. @Service  
  14. public class UserServiceImpl implements UserService {  
  15.   
  16.     //User接口  
  17.     @Autowired  
  18.     private UserMapper userMapper;  
  19.   
  20.     public List findUser() throws Exception {  
  21.         //调用mapper类中的selectByExample方法,如果传入类型为null,则表示无条件查找  
  22.         List users = userMapper.selectByExample(null);  
  23.   
  24.         return users;  
  25.     }  
  26. }  

Controller

[java]  view plain  copy
 
  1. package com.elin4it.ssm.controller;  
  2.   
  3. import com.elin4it.ssm.pojo.User;  
  4. import com.elin4it.ssm.service.UserService;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Controller;  
  7. import org.springframework.web.bind.annotation.RequestMapping;  
  8. import org.springframework.web.servlet.ModelAndView;  
  9.   
  10. import java.util.List;  
  11.   
  12. /** 
  13.  * Created by 烽 on 2015/7/11. 
  14.  */  
  15. @Controller  
  16. @RequestMapping("/user")  
  17. public class UserController {  
  18.   
  19.     //service类  
  20.     @Autowired  
  21.     private UserService userService;  
  22.   
  23.     /** 
  24.      * 查找所用用户控制器方法 
  25.      * @return 
  26.      * @throws Exception 
  27.      */  
  28.     @RequestMapping("/findUser")  
  29.     public ModelAndView findUser()throws Exception{  
  30.         ModelAndView modelAndView = new ModelAndView();  
  31.   
  32.         //调用service方法得到用户列表  
  33.         List users = userService.findUser();  
  34.         //将得到的用户列表内容添加到ModelAndView中  
  35.         modelAndView.addObject("users",users);  
  36.         //设置响应的jsp视图  
  37.         modelAndView.setViewName("findUser");  
  38.   
  39.         return modelAndView;  
  40.     }  
  41. }  

视图

根据之前写的controller,返回的视图为findUser,所以在/WEB-INF/views中创建findUser.jsp文件,用来显示查询出来的结果

[html]  view plain  copy
 
  1. <%--  
  2.   Created by IntelliJ IDEA.  
  3.   User: 烽  
  4.   Date: 2015/7/11  
  5.   Time: 19:47  
  6.   To change this template use File | Settings | File Templates.  
  7. --%>  
  8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>  
  9. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  10. <html>  
  11. <head>  
  12.     <title>title>  
  13. head>  
  14. <body>  
  15. <h1>findUserh1>  
  16. <table>  
  17.   <c:forEach items="${users}" var="u">  
  18.     <tr>  
  19.       <td>${u.id}td>  
  20.       <td>${u.username}td>  
  21.       <td>${u.birthday}td>  
  22.     tr>  
  23.   c:forEach>  
  24.   
  25. table>  
  26. body>  
  27. html>  

你可能感兴趣的:(ssm)