zoukankan      html  css  js  c++  java
  • mybatis+springMVC

    !!!springMVC  Mybatis dbcp  log4j

    1、导入jar包

     

    2、spring-servlet.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-2.5.xsd
               http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
               http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    
        <!-- 使spring扫描包下的所有类,让标注spring注解的类生效 -->
        <context:component-scan base-package="com.duanzishou">
            <!-- 扫描所有的controller 但是不扫描service--> 
             <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> 
             <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> 
        </context:component-scan>
    
        <mvc:annotation-driven></mvc:annotation-driven>
    
        <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
        <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/view/" />
            <property name="suffix" value=".jsp" />
        </bean>
    
        <!-- JSON支持 -->
        <bean id="messageAdapter"
            class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
            <property name="messageConverters">
                <list>
                    <!-- Support JSON -->
                    <bean
                        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
                </list>
            </property>
        </bean>
        <mvc:resources mapping="/resources/**" location="/resources/" />
        <mvc:resources mapping="/js/**" location="/js/" />
        <mvc:resources mapping="/images/**" location="/images/" />
        <mvc:resources mapping="/css/**" location="/css/" />
        <mvc:resources mapping="/common/**" location="/common/" />
        <mvc:resources mapping="/bootstrap/**" location="/bootstrap/" />
        <mvc:resources mapping="/lib/**" location="/lib/" />
        <mvc:resources mapping="/twitter-bootstrap/**" location="/twitter-bootstrap/" />
        <mvc:resources mapping="/upload/**" location="/upload/" />
        <bean id="exceptionMessageAdapter"
            class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
            <property name="messageConverters">
                <list>
                    <!-- Support JSON -->
                    <bean
                        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
                </list>
            </property>
        </bean>
    
        <!-- 文件上传支持 -->
        <bean id="multipartResolver"
            class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
            p:maxUploadSize="34564356345456" 
            p:defaultEncoding="utf-8">
            <!-- <property name="defaultEncoding" value="utf-8"></property> -->
        </bean>
    
    
    
    </beans> 

      3、applicationContext-mybatis.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:aop="http://www.springframework.org/schema/aop"
        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-2.5.xsd   
                    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd   
                    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
        <!-- Properties文件读取配置,base的properties -->
        <context:property-placeholder location="classpath:jdbc.properties" />
    
        <!-- JNDI获取数据源(使用dbcp连接池) -->
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close" scope="singleton">
            <property name="driverClassName" value="${driverClassName}" />
            <property name="url" value="${url}" />
            <property name="username" value="${uname}" />
            <property name="password" value="${password}" />
            <!-- 初始化连接大小 -->
            <property name="initialSize" value="${initialSize}"></property>
            <!-- 连接池最大数量 -->
            <property name="maxActive" value="${maxActive}"></property>
            <!-- 连接池最大空闲 -->
            <property name="maxIdle" value="${maxIdle}"></property>
            <!-- 连接池最小空闲 -->
            <property name="minIdle" value="${minIdle}"></property>
            <!-- 获取连接最大等待时间 -->
            <property name="maxWait" value="${maxWait}"></property>
        </bean>
        <!-- enable transaction demarcation with annotations -->
        <tx:annotation-driven />
    
        <!-- 定义 SqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
            scope="singleton">
            <property name="dataSource" ref="dataSource" />
            <property name="configLocation" value="classpath:mybatis-config.xml" />
        </bean>
    
        <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
        <bean id="transactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>
    
        <!-- 配置事务通知属性 -->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <!-- 定义事务传播属性 -->
            <tx:attributes>
                <tx:method name="insert*" propagation="REQUIRED" />
                <tx:method name="update*" propagation="REQUIRED" />
                <tx:method name="edit*" propagation="REQUIRED" />
                <tx:method name="save*" propagation="REQUIRED" />
                <tx:method name="add*" propagation="REQUIRED" />
                <tx:method name="new*" propagation="REQUIRED" />
                <tx:method name="set*" propagation="REQUIRED" />
                <tx:method name="remove*" propagation="REQUIRED" />
                <tx:method name="delete*" propagation="REQUIRED" />
                <tx:method name="change*" propagation="REQUIRED" />
                <tx:method name="get*" propagation="REQUIRED" read-only="true" />
                <tx:method name="query*" propagation="REQUIRED" read-only="true" />
                <tx:method name="find*" propagation="REQUIRED" read-only="true" />
                <tx:method name="load*" propagation="REQUIRED" read-only="true" />
                <tx:method name="*" propagation="REQUIRED" read-only="true" />
                <tx:method name="*" rollback-for="CustomException" />
            </tx:attributes>
        </tx:advice>
    
        <!-- 应用普通类获取bean <bean id="appContext" class="com.soanl.util.tool.ApplicationUtil"/> -->
    
        <!-- 配置事务切面 -->
        <aop:config>
            <aop:pointcut id="serviceOperation"
                expression="execution(* com.duanzishou.service..*.*(..))" />
            <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
        </aop:config>
    
    
    
    
    
    
        <!-- scan for mappers and let them be autowired MapperScannerConfigurer 
            Mybatis-Spring 会自动为我们注册Mapper对应的MapperFactoryBean对象 -->
        <!-- Mapper接口所在包名,Spring会自动查找其下的Mapper -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="org.project.dao" />
        </bean>
        
        <!-- 自动扫描组件,这里要把controler下面的 controller去除,他们是在springmvc的配置文件中配置的,如果不去除会影响事务管理的。  -->
        <context:component-scan base-package="com.duanzishou.*">
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> 
        </context:component-scan>
    
    
    
    </beans>  

    4.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" />  
                    <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指定),不会加载关联表的所有字段,以提高性能 -->  
            <setting name="aggressiveLazyLoading" value="false" />  
                    <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->  
            <setting name="multipleResultSetsEnabled" value="true" />  
                    <!-- 允许使用列标签代替列名 -->  
            <setting name="useColumnLabel" value="true" />  
                    <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->  
            <setting name="useGeneratedKeys" value="true" />  
                    <!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->  
            <setting name="autoMappingBehavior" value="FULL" />  
                    <!-- 对于批量更新操作缓存SQL以提高性能  -->  
            <setting name="defaultExecutorType" value="BATCH" />  
                    <!-- 数据库超过25000秒仍未响应则超时 -->  
            <setting name="defaultStatementTimeout" value="25000" />  
            </settings> 
           <typeAliases>  
               <!--这里给实体类取别名,方便在mapper配置文件中使用--> 
               <!-- <typeAlias alias="user" type="org.project.pojo.User"/>  -->
               <package name="com.duanzishou.entity"/>
           </typeAliases>  
           
           <!-- 设置Mybatis的映射文件 -->
        <mappers>
            <!-- <mapper resource="com/duanzishou/entity/UserMapper.xml" /> -->
            <package name="com/duanzishou/entity" />
        </mappers>
           
           
       </configuration>  

     5、web.xml整合SpringMVC和Mybatis

    <?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_3_0.xsd" version="3.0">
      <display-name></display-name>
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext-*.xml</param-value>
      </context-param>
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
       <!-- 初始化 DispatcherServlet时,该框架在 web应用程序WEB-INF目录中寻找一个名为[servlet-名称]-servlet.xml的文件,  
                并在那里定义相关的Beans,重写在全局中定义的任何Beans -->
      <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <!-- 所有的的请求,都会被DispatcherServlet处理 -->  
        <url-pattern>/</url-pattern>
      </servlet-mapping>
      <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.properties</param-value>
      </context-param>
        <!-- 日志监听 -->  
      <listener>
        <listener-class>
                org.springframework.web.util.Log4jConfigListener
            </listener-class>
      </listener>
       <!-- 配置字符集 -->  
      <filter>
        <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
        <url-pattern>/</url-pattern>
      </filter-mapping>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>

    5、log4j.properties

    log4j.rootLogger=debug,CONSOLE,file
    #log4j.rootLogger=ERROR,ROLLING_FILE
    
    log4j.logger.org.project=error
    log4j.logger.org.apache.ibatis=debug
    log4j.logger.org.mybatis.spring=debug
    log4j.logger.java.sql.Connection=debug
    log4j.logger.java.sql.Statement=debug
    log4j.logger.java.sql.PreparedStatement=debug
    log4j.logger.java.sql.ResultSet=debug
    
    ######################################################################################
    # Console Appender  u65e5u5fd7u5728u63a7u5236u8f93u51fau914du7f6e
    ######################################################################################
    log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
    log4j.appender.Threshold=debug
    log4j.appender.CONSOLE.Target=System.out
    log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
    log4j.appender.CONSOLE.layout.ConversionPattern= - (%r ms) - [%p] %d %c - %m%n
    
    ######################################################################################
    # Rolling File  u6587u4ef6u5927u5c0fu5230u8fbeu6307u5b9au5c3au5bf8u7684u65f6u5019u4ea7u751fu4e00u4e2au65b0u7684u6587u4ef6
    ######################################################################################
    #log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender
    #log4j.appender.ROLLING_FILE.Threshold=INFO
    #log4j.appender.ROLLING_FILE.File=${baojia.root}/logs/log.log
    #log4j.appender.ROLLING_FILE.Append=true
    #log4j.appender.ROLLING_FILE.MaxFileSize=5000KB
    #log4j.appender.ROLLING_FILE.MaxBackupIndex=100
    #log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout
    #log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
    
    ######################################################################################
    # DailyRolling File  u6bcfu5929u4ea7u751fu4e00u4e2au65e5u5fd7u6587u4ef6uff0cu6587u4ef6u540du683cu5f0f:log2009-09-11
    ######################################################################################
    log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.file.DatePattern=yyyy-MM-dd
    log4j.appender.file.File=${springMVCProject.root}/logs/log.log
    log4j.appender.file.Append=true
    log4j.appender.file.Threshold=debug
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern= - (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
    
    #DWR u65e5u5fd7
    #log4j.logger.org.directwebremoting = ERROR
    
    #u663eu793aHibernateu5360u4f4du7b26u7ed1u5b9au503cu53cau8fd4u56deu503c
    #log4j.logger.org.hibernate.type=DEBUG,CONSOLE 
    
    #log4j.logger.org.springframework.transaction=DEBUG
    #log4j.logger.org.hibernate=DEBUG
    #log4j.logger.org.acegisecurity=DEBUG
    #log4j.logger.org.apache.myfaces=TRACE
    #log4j.logger.org.quartz=DEBUG
    
    #log4j.logger.com.opensymphony=INFO  
    #log4j.logger.org.apache.struts2=DEBUG  
    log4j.logger.com.opensymphony.xwork2=debug

    6、jdbc.properties

    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql://127.0.0.1:3306/waduanzi?useUnicode=true&characterEncoding=utf-8
    uname=root
    password=123456
    minIdle=10
    maxIdle=50
    initialSize=5
    maxActive=100
    maxWait=100
    removeAbandonedTimeout=180
    removeAbandoned=true
  • 相关阅读:
    .Net Core使用Options模式来使用配置项
    git忽略已经提交的文件(git忽略文件不起作用)
    AirTest
    VSCode搭建rust开发环境
    动态编译和加载java代码
    JavaScript动态应用代码(有点像Java里的drools)
    Win10 Rust 编译报错: linking with `link.exe` failed: exit code: 1181
    git 拉取仓库的单个目录
    dart里实现类似Java里的--classpath的功能
    Rust离线安装
  • 原文地址:https://www.cnblogs.com/xdcr/p/5908294.html
Copyright © 2011-2022 走看看