springmvc+mybatis-generator+maven

from:https://www.youtube.com/watch?v=kBgaxF6vsJk&list=PL3rfV4zNE8CCdBbej0R0kZcsmIsuwRrjI

1、mybatis:
根据存在于数据库中的表去生成domain、DAO和xml文件,所以首先要有mysql表其次要有generate.xml文件

根据mybatis-generator-XX.jar生成domain、mapper(即DAO)、mapping(即mybatis对应domain的xml文件):
java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite

mybatis-generate.xml内容示例如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
 <!-- 数据库驱动包位置 -->
 <!-- <classPathEntry location="D:\software\lib\mysql-connector-java-5.1.21.jar" /> -->
 <classPathEntry location="C:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc14.jar" />
 <context id="DB2Tables" targetRuntime="MyBatis3">
  <commentGenerator>
   <property name="suppressAllComments" value="true" />
  </commentGenerator>
  <!-- 数据库链接URL、用户名、密码 -->
  <!-- <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/sy" userId="sypro" password="sypro"> -->
  <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId="msa" password="msa">
  </jdbcConnection>
  <javaTypeResolver>
   <property name="forceBigDecimals" value="false" />
  </javaTypeResolver>
  <!-- 生成模型的包名和位置 -->
  <javaModelGenerator targetPackage="sy.model" targetProject="D:\study\mybatis\src">
   <property name="enableSubPackages" value="true" />
   <property name="trimStrings" value="true" />
  </javaModelGenerator>
  <!-- 生成的映射文件包名和位置 -->
  <sqlMapGenerator targetPackage="sy.xml" targetProject="D:\study\mybatis\src">
   <property name="enableSubPackages" value="true" />
  </sqlMapGenerator>
  <!-- 生成DAO的包名和位置 -->
  <javaClientGenerator type="XMLMAPPER" targetPackage="sy.dao" targetProject="D:\study\mybatis\src">
   <property name="enableSubPackages" value="true" />
  </javaClientGenerator>
  <!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
  <table tableName="tbug" domainObjectName="Bug" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
  <table tableName="tmenu" domainObjectName="Menu" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
  <table tableName="tonline" domainObjectName="Online" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
  <table tableName="tresource" domainObjectName="Resource" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
  <table tableName="trole" domainObjectName="Role" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
  <table tableName="trole_tresource" domainObjectName="RoleResource" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
  <table tableName="tuser" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
  <table tableName="tuser_trole" domainObjectName="UserRole" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
 </context>
</generatorConfiguration>

2、spring和mybatis整合
1)、在pom.xml中引入spring-core、mybatis、mybatis-spring、druid(数据源)、aspect依赖
2)、src\main\resources下引入config.properties,log4j.properties,spring.xml,springmvc.xml,spring-mybatis.xml
spring.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" 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
">

 <!-- 引入属性文件 -->
 <context:property-placeholder location="classpath:config.properties" />

 <!-- 自动扫描(自动注入) -->
 <context:component-scan base-package="sy.service" />


</beans>

log4j.properties:
log4j.rootLogger=DEBUG,Console,File

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=[%c]%m%n

log4j.appender.File=org.apache.log4j.RollingFileAppender 
log4j.appender.File.File=mybatis.log
log4j.appender.File.MaxFileSize=10MB
log4j.appender.File.Threshold=ALL
log4j.appender.File.layout=org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n



config.properties:
#hibernate.dialect=org.hibernate.dialect.OracleDialect
#driverClassName=oracle.jdbc.driver.OracleDriver
#validationQuery=SELECT 1 FROM DUAL
#jdbc_url=jdbc:oracle:thin:@localhost:1521:orcl
#jdbc_username=sypro
#jdbc_password=sypro

hibernate.dialect=org.hibernate.dialect.MySQLDialect
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/sy?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=sypro
jdbc_password=sypro

#hibernate.dialect=org.hibernate.dialect.SQLServerDialect
#driverClassName=net.sourceforge.jtds.jdbc.Driver
#validationQuery=SELECT 1
#jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy
#jdbc_username=sa
#jdbc_password=123456

#hibernate.dialect=org.hibernate.dialect.DerbyDialect
#driverClassName=org.apache.derby.jdbc.EmbeddedDriver
#validationQuery=SELECT 1
#jdbc_url=jdbc:derby:sy;create=true
#jdbc_username=sypro
#jdbc_password=sypro

#jndiName=java:comp/env/dataSourceName

hibernate.hbm2ddl.auto=update
hibernate.show_sql=false
hibernate.format_sql=true

sessionInfoName=sessionInfo

uploadFieldName=filedata
uploadFileMaxSize=20971520
uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid
uploadDirectory=attached

spring-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: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-3.0.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">

 <!-- JNDI方式配置数据源 -->
 <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> -->

 <!-- 配置数据源 -->
 <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
  <property name="url" value="${jdbc_url}" />
  <property name="username" value="${jdbc_username}" />
  <property name="password" value="${jdbc_password}" />

  <!-- 初始化连接大小 -->
  <property name="initialSize" value="0" />
  <!-- 连接池最大使用连接数量 -->
  <property name="maxActive" value="20" />
  <!-- 连接池最大空闲 -->
  <property name="maxIdle" value="20" />
  <!-- 连接池最小空闲 -->
  <property name="minIdle" value="0" />
  <!-- 获取连接最大等待时间 -->
  <property name="maxWait" value="60000" />

  <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->

  <property name="validationQuery" value="${validationQuery}" />
  <property name="testOnBorrow" value="false" />
  <property name="testOnReturn" value="false" />
  <property name="testWhileIdle" value="true" />

  <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
  <property name="timeBetweenEvictionRunsMillis" value="60000" />
  <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
  <property name="minEvictableIdleTimeMillis" value="25200000" />

  <!-- 打开removeAbandoned功能 -->
  <property name="removeAbandoned" value="true" />
  <!-- 1800秒,也就是30分钟 -->
  <property name="removeAbandonedTimeout" value="1800" />
  <!-- 关闭abanded连接时输出错误日志 -->
  <property name="logAbandoned" value="true" />

  <!-- 监控数据库 -->
  <!-- <property name="filters" value="stat" /> -->
  <property name="filters" value="mergeStat" />
 </bean>

 <!-- myBatis文件 -->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
  <property name="mapperLocations" value="classpath:sy/mapping/*.xml" />
 </bean>
 
 <!--mybatis mapper类-->
 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="sy.dao" />
  <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
 </bean>

 <!-- 配置事务管理器 -->
 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource" />
 </bean>

 <!-- 注解方式配置事物 -->
 <!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->

 <!-- 拦截器方式配置事物 -->
 <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(* sy.service..*Impl.*(..))" />
  <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
 </aop:config>


 <!-- 配置druid监控spring jdbc -->
 <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
 </bean>
 <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
  <property name="patterns">
   <list>
    <value>sy.service.*</value>
   </list>
  </property>
 </bean>
 <aop:config>
  <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
 </aop:config>

</beans>

测试:
junit4:
Before注解中读取spring.xml和spring-mybatis.xml的applicationContext,同时读取userService

使用SpringJunit4ClassRunner:
引入spring-test依赖;
在测试类上使用注解@RunWith(SpringJunit4ClassRunner.class)(类似于测试类继承了SpringJunit4ClassRunner);同时使用注解@ContextConfiguration,配置了spring.xml和spring-mybatis.xml的位置,类中使用@Autowired自动注入userService


springmvc:
springmvc.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" 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">

 <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
 <context:component-scan base-package="sy.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>

 <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="messageConverters">
   <list>
    <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
   </list>
  </property>
 </bean>

 <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" />

 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="defaultEncoding">
   <value>UTF-8</value>
  </property>
  <property name="maxUploadSize">
   <value>32505856</value><!-- 上传文件大小限制为31M,31*1024*1024 -->
  </property>
  <property name="maxInMemorySize">
   <value>4096</value>
  </property>
 </bean>

</beans>

Controller:
在类上加注解@Controller和@RequestMapping;
Controller中注入userService
http://local/web/user/0/info
方法名称上@PathVariable("id")

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 <display-name>mybatis</display-name>
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value>
 </context-param>
 <filter>
  <description>字符集过滤器</description>
  <filter-name>encodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
   <description>字符集编码</description>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>encodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <listener>
  <description>spring监听器</description>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <!-- 防止spring内存溢出监听器 -->
 <listener>
  <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
 </listener>
 <!-- spring mvc servlet -->
 <servlet>
  <description>spring mvc servlet</description>
  <servlet-name>springMvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <description>spring mvc 配置文件</description>
   <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>*.do</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
  <welcome-file>/index.jsp</welcome-file>
 </welcome-file-list>
 <!-- 配置session超时时间,单位分钟 -->
 <session-config>
  <session-timeout>15</session-timeout>
 </session-config>
</web-app>