zoukankan      html  css  js  c++  java
  • spring+springmvc+mybatis整合

    1、导包

    整合SSM
    0.导包
    spring
    spring-beans-4.0.0.RELEASE.jar
    spring-context-4.0.0.RELEASE.jar
    spring-core-4.0.0.RELEASE.jar
    spring-expression-4.0.0.RELEASE.jar
    commons-logging-1.1.3.jar
    spring-aop-4.0.0.RELEASE.jar(使用注解的功能,必须导入aop)
    支持AOP:
    spring-aspects-4.0.0.RELEASE.jar
    AspectJ:Java社区里最完整最流行的AOP框架
    com.springsource.org.aopalliance-1.0.0.jar
    com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
    com.springsource.net.sf.cglib-2.2.0.jar(实现动态代理)
    JdbcTemplate所需要的JAR包
    spring-orm-4.0.0.RELEASE.jar
    spring-tx-4.0.0.RELEASE.jar
    spring-jdbc-4.0.0.RELEASE.jar
    数据库连接池和驱动
    c3p0-0.9.1.2.jar
    mysql-connector-java-5.1.7-bin.jar
    spring-mvc
    spring-web-4.0.0.RELEASE.jar
    spring-webmvc-4.0.0.RELEASE.jar
    mybatis
    mybatis-spring-1.3.0.jar
    mybatis-3.4.1.jar
    log4j-1.2.17.jar
    ehcache第三方缓存
    ehcache-core-2.6.8.jar
    mybatis-ehcache-1.0.3.jar
    slf4j-api-1.6.1.jar
    slf4j-log4j12-1.6.2.jar
    其它
    EL表达式 & JSTL标签库
    taglibs-standard-impl-1.2.1.jar
    taglibs-standard-spec-1.2.1.jar
    JSR303数据校验---实现---》加入hibernate validator验证框架
    hibernate-validator-5.0.0.CR2.jar
    hibernate-validator-annotation-processor-5.0.0.CR2.jar
    required
    classmate-0.8.0.jar
    jboss-logging-3.1.1.GA.jar
    validation-api-1.1.0.CR1.jar
    springmvc支持AJAX
    jackson-annotations-2.1.5.jar
    jackson-core-2.1.5.jar
    jackson-databind-2.1.5.jar
    google验证码
    kaptcha-2.3.2.jar
    springmvc文件上传下载
    commons-fileupload-1.2.1.jar
    commons-io-2.0.jar

    2、写配置

    web.xml

    <?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/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
      <display-name>8.SSM</display-name>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <!-- 启动Spring的IOC容器 -->
      <!--利用 ContextLoaderListener监听器创建销毁springIOC容器 -->
      <!-- needed for ContextLoaderListener -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </context-param>
    
        <!-- Bootstraps the root web application context before servlet initialization -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
      
      <!-- SpringMVC的前端控制器 -->
      <!-- springMVC的入口 -->
        <servlet>
            <servlet-name>springDispatcherServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:applicationContext-mvc.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <!-- Map all requests to the DispatcherServlet for handling -->
        <!-- /:“/”过滤除。jsp外的资源 -->
        <servlet-mapping>
            <servlet-name>springDispatcherServlet</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
            
        <!--标配  -->
        <!--设置编码  -->
        <filter>
            <filter-name>CharacterEncodingFilter</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <!--设置request的编码格式  -->
            <init-param>
                <param-name>encoding</param-name>
                <param-value>utf-8</param-value>
            </init-param>
            <!-- reponse的编码是否与request一样 -->
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>CharacterEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        <!-- HiddenHttpMethodFilter将from下的post和get转化支持REST模式 -->
        <filter>
            <filter-name>HiddenHttpMethodFilter</filter-name>
            <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>HiddenHttpMethodFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>    
    </web-app>

     applicationContext.xml

    <?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: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-4.0.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
        <!-- 1、扫描所有组件,除了Controller层的组件,因为其交给springmvc进行处理,防止重复注册 -->
        <context:component-scan base-package="com.atguigu">
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
            <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
        </context:component-scan>
        <!--2、设置数据源和事务管理器  -->
        <!--加载配置文件,设置数据库连接池  -->
        <context:property-placeholder location="classpath:dbconfig.properties"/>
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="user" value="${prop.user}"></property>
            <property name="password" value="${prop.password}"></property>
            <property name="jdbcUrl" value="${prop.jdbcUrl}"></property>
            <property name="driverClass" value="${prop.driverClass}"></property>    
        </bean>
    <!--3、配置事务管理  -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!--2)、配置事务切面  -->
        <aop:config>
            <!-- 配置事务切入点 -->
            <aop:pointcut expression="execution(* com.atguigu.service.*.*(..))" id="txPoint"/>
             <!--事务增强器  -->
             <!-- 将切入点表达式和事务属性配置关联到一起 -->
             <aop:advisor advice-ref="myTxAdvice" pointcut-ref="txPoint"/>
        </aop:config>
         <!-- 事务增强;事务属性 -->
        <!-- 配置基于XML的声明式事务  -->
        <tx:advice id="myTxAdvice" transaction-manager="transactionManager">
             <!--配置切入的每一个事务方法的细节  -->
            <tx:attributes>
                <tx:method name="*" rollback-for="java.lang.Exception"/>
                <tx:method name="get*" read-only="true"/>
            </tx:attributes>
        </tx:advice>
        <!--  启用事务注解 
        <tx:annotation-driven transaction-manager="transactionManager"/> -->
        
        <!-- spring原生的操作数据库采用jdbcTemplate,现在整合mybatis来进行处理 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 加载配置文件进行配置 -->
            <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
            <!-- 整合数据源,与spring关联起来 -->
            <property name="dataSource" ref="dataSource"></property>
            <!-- 批量起别名 -->
            <property name="typeAliasesPackage" value="com.atguigu.bean"></property>
            <!-- 配置xml映射文件的位置 -->
            <property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"></property>
        </bean>
        <!--  把每个dao接口的实现加入到ioc容器中-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.atguigu.dao"></property>
        </bean>
    </beans>

    applicationContext-mvc.xml

    <?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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
            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-4.0.xsd">
        <!-- 1.扫描springMVC的组件 -->
        <context:component-scan base-package="com.atguigu">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
            <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
        </context:component-scan>
        <!--2.配置视图解析器,简化返回值  -->    
        <bean id="" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/pages/"></property>
            <property name="suffix" value=".jsp"></property>
       </bean>
       <!-- 3.开启开挂功能 -->
           <!-- 映射动态请求 -->
       <mvc:annotation-driven></mvc:annotation-driven>
       <!-- 映射静态资源 -->
       <mvc:default-servlet-handler/>   
    </beans>

    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"/>
      </settings>
    <!--   <mappers>
          写好的每一个dao接口的实现文件(sql映射文件)都必须在全局配置文件中注册
        <mapper resource="mybatis/mapper/PersonDao.xml"/>
      </mappers> -->
    </configuration>

    PersonDao.xml

    <?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="com.atguigu.dao.PersonDao">
      
    <!-- 第一处:
        namespace:命名空间;必须是dao的接口全类名;mybatis就只到这个配置文件是对哪个接口的实现 -->
    <!-- public void saveStudent(Student stu); -->
      <!--定义一个保存操作;id和方法名一致  -->
      <select id="getPersonById" resultType="com.atguigu.bean.Person" >
          select * from tbl_person where id=#{id}
      </select> 
    </mapper>

    ehcache.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">  
        <!-- 
            磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存
            path:指定在硬盘上存储对象的路径
         -->
        <diskStore path="D:Javaehcache" />
        <defaultCache 
        maxElementsInMemory="10000" 
        maxElementsOnDisk="100000000"
        eternal="false"
        timeToIdleSeconds="120" 
        timeToLiveSeconds="120" 
        overflowToDisk="true"
        diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU" />
    </ehcache>
    <!-- 
    属性说明:
    l diskStore:指定数据在磁盘中的存储位置。
    l defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略
     
    以下属性是必须的:
    l maxElementsInMemory - 在内存中缓存的element的最大数目 
    l maxElementsOnDisk - 在磁盘上缓存的element的最大数目,若是0表示无穷大
    l eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
    l overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上
     
    以下属性是可选的:
    l timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大
    l timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大
     diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.
    l diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。
    l diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作
    l memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出)
     -->

    3、写程序

    查询员工信息并显示

    index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <a href="person/7">GET-Person</a>
    </body>
    </html>

    PersonController.java

    @Controller
    public class PersonController {
        
        @Autowired
        PersonService personService;
        
        //查询某个员工并展示其信息
        @RequestMapping(value="/person/{id}",method=RequestMethod.GET)
        public String getPerson(@PathVariable("id")Integer id,Model model){
            Person person = personService.getPerson(id);
            model.addAttribute("person", person);
            return "success";
        }
    
    }

    success.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    Person-INFO:<br/>
    ${person}
    </body>
    </html>

    mybatis流程:

    1.dao.java与XML的映射文件进行绑定

    2.mybatis.xml配置mybatis的配置和属性

    3.从 XML 中构建 SqlSessionFactory

    String resource = "org/mybatis/example/mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    4.从 SqlSessionFactory 中获取 SqlSession,最终调用方法执行

    SqlSession session = sqlSessionFactory.openSession();
    try {
      BlogMapper mapper = session.getMapper(BlogMapper.class);
      Blog blog = mapper.selectBlog(101);
    } finally {
      session.close();
    }

    mybatis和spring整合

    1.dao.java与XML的映射文件进行绑定

    2.mybatis.xml配置mybatis的配置和属性(数据源采用spring的)

     <property name="dataSource" ref="dataSource"></property>

    3. 采用SqlSessionFactoryBean构建 SqlSessionFactory(整合需要导入mybatis-spring-1.3.0.jar)

    整合mybatis想清楚一些东西由何而来;SqlSession---->SqlSessionFactory---->读取mybatis配置文件的

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 加载配置文件进行配置 -->
            <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
            <!-- 整合数据源,与spring关联起来 -->
            <property name="dataSource" ref="dataSource"></property>
            <!-- 批量起别名 -->
            <property name="typeAliasesPackage" value="com.atguigu.bean"></property>
            <!-- 配置xml映射文件的位置 -->
            <property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"></property>
        </bean>
        <!--  把每个dao接口的实现加入到ioc容器中-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.atguigu.dao"></property>
        </bean>

    mybatis与其他框架的结合参考官网:

    https://github.com/mybatis/

    与spring结合例子及注意事项

     

  • 相关阅读:
    PostgreSQL主从流复制部署
    MySQL集群主从复制搭建
    zabbix修改支持中文主机名
    BGP总结(三)
    BGP总结(二)
    BGP总结(一)
    VXLAN配置实例(华为)
    VXLAN理论解析
    飞塔创建IPSec
    关于SANGFOR AC记录上网记录
  • 原文地址:https://www.cnblogs.com/limingxian537423/p/7372755.html
Copyright © 2011-2022 走看看