首页 > 学院 > 开发设计 > 正文

spring4和mybaties3整合(一)

2019-11-11 05:12:40
字体:
来源:转载
供稿:网友

整合后的目录结构

sPRing配置文件

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:cache="http://www.springframework.org/schema/cache"	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task"	xmlns:websocket="http://www.springframework.org/schema/websocket"	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd	http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd	http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-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/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd"	default-lazy-init="false">	<!-- 配置数据源 -->	<context:component-scan base-package="com.weichu.controller" />	<context:component-scan base-package="com.weichu.dao" />	<context:component-scan base-package="com.weichu.service" />		<context:property-placeholder location="classpath:config/system.properties" />	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">		<property name="driverClass" value="${jdbc.driver}" />		<property name="jdbcUrl" value="${jdbc.url}" />		<property name="user" value="${jdbc.username}" />		<property name="passWord" value="${jdbc.password}" />		<property name="initialPoolSize" value="${connection_pools.initial_pool_size}" />		<property name="minPoolSize" value="${connection_pools.min_pool_size}" />		<property name="maxPoolSize" value="${connection_pools.max_pool_size}" />		<property name="maxIdleTime" value="${connection_pools.max_idle_time}" />		<property name="acquireIncrement" value="${connection_pools.acquire_increment}" />		<property name="checkoutTimeout" value="${connection_pools.checkout_timeout}" />	</bean>		 <!-- DAO接口所在包名,Spring会自动查找其下的类 -->     	  <bean id="sqlsessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">          <property name="dataSource" ref="dataSource" />          <!-- 自动扫描mapping.xml文件 -->        <property name="configLocation" value="classpath:config/mybatis-config.xml"></property>          <property name="mapperLocations" value="classpath:config/sqlxml/*.xml"></property>      </bean>        <!-- DAO接口所在包名,Spring会自动查找其下的类 -->      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">         <property name="basePackage" value="com.weichu.dao" />          <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>      </bean>        <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->      <bean id="transactionManager"          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">          <property name="dataSource" ref="dataSource" />      </bean>  		 <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">		<constructor-arg  ref="sqlSessionFactory" />	 </bean>     	<!-- <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean"> 		<property name="mapperInterface" value="com.springMyBatis.system.dao.UserDao"></property> 		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> -->	<!-- <bean id="tokenServiceImpl" class="com.asiainfo.service.impl.TokenServiceImpl"> 		<property name="tokenDaoImpl" value="com.asiainfo.dao.impl.TokenDaoImpl" 		/> </bean> --></beans>

spring mvc配置文件

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" xmlns:websocket="http://www.springframework.org/schema/websocket"	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd       http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd"	default-lazy-init="true">	<!-- 注解扫描包 -->	<context:component-scan base-package="com.weichu.controller" />	<context:component-scan base-package="com.weichu.dao" />	<context:component-scan base-package="com.weichu.service" />	<!-- 开启注解 -->	<bean		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />	<bean		class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>	<!-- 静态资源访问 -->	<mvc:annotation-driven />	<mvc:resources location="/resources/" mapping="/resources/**" />	<mvc:resources location="/pages/" mapping="/pages/**" />    <mvc:resources location="/" mapping="/**/*.js"/>      <mvc:resources location="/" mapping="/**/*.CSS"/>      <mvc:resources location="/" mapping="/**/*.png"/>      <mvc:resources location="/" mapping="/**/*.gif"/>      <mvc:resources location="/" mapping="/**/*.jpg"/>      <mvc:resources location="/" mapping="/**/*.jpeg"/>  		<bean id="viewResolver"		class="org.springframework.web.servlet.view.InternalResourceViewResolver">		<property name="prefix" value="/"></property>		<property name="suffix" value=".jsp"></property>		<property name="contentType" value="text/html;charset=UTF-8" />	</bean>	<!--定义异常处理页面 -->	<!-- <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> 		<property name="exceptionMappings"> <props> <prop key="java.lang.Exception">system/error</prop> 		</props> </property> </bean> -->	<bean id="multipartResolver"		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">		<property name="defaultEncoding" value="utf-8"></property>		<property name="maxUploadSize" value="10485760000"></property>		<property name="maxInMemorySize" value="40960"></property>	</bean>	<bean id="stringConverter"		class="org.springframework.http.converter.StringHttpMessageConverter">		<property name="supportedMediaTypes">			<list>				<value>text/plain;charset=UTF-8</value>			</list>		</property>	</bean>	<bean id="jsonConverter"		class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">		<property name="objectMapper">			<bean class="com.fasterxml.jackson.databind.ObjectMapper">				<property name="dateFormat">					<bean class="java.text.SimpleDateFormat">						<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />					</bean>				</property>			</bean>		</property>	</bean>	<bean		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">		<property name="messageConverters">			<list>				<ref bean="stringConverter" />				<ref bean="jsonConverter" />			</list>		</property>	</bean>    </beans>mybaties配置文件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>	<properties resource="config/system.properties">	</properties>	<!-- 配置多环境信息,由default指定默认使用的环境 -->	<!-- 	<environments default="development"> 	<environment id="development"> 		<transactionManager type="JDBC" /> 		<dataSource type="POOLED"> 		<property name="driver" value="${jdbc.driver}" />	    <property name="url" value="${jdbc.url}" /> 	    <property name="username" value="${jdbc.username}" /> 	    <property name="password" value="${jdbc.password}" /> 	    </dataSource> 	</environment> 	</environments> 	-->	 <settings>		<setting name="cacheEnabled" value="false" />		<setting name="lazyLoadingEnabled" value="true" />		<setting name="multipleResultSetsEnabled" value="true" />		<setting name="useColumnLabel" value="true" />		<setting name="defaultExecutorType" value="REUSE" />		<setting name="defaultStatementTimeout" value="25000" />		<setting name="logImpl" value="LOG4J" />	</settings> 	<!-- <mappers>		<mapper resource="config/sqlxml/StudentMapper.xml" />	</mappers>  -->    </configuration>

数据库配置文件

system.properties

#------------ JDBC ------------jdbc.driver=com.MySQL.jdbc.Driverjdbc.url=jdbc:mysql://127.0.0.1:3306/wechat?useUnicode=true&characterEncoding=UTF-8jdbc.username=rootjdbc.password=123456#------------ ConnectionPools ------------connection_pools.initial_pool_size=5connection_pools.min_pool_size=5connection_pools.max_pool_size=100connection_pools.max_idle_time=600connection_pools.acquire_increment=5connection_pools.checkout_timeout=60000web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">  <display-name>weichu</display-name>  <context-param>    <param-name>log4jConfigLocation</param-name>    <param-value>classpath:log4j.properties</param-value>  </context-param>  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>            classpath*:config/applicationContext.xml        </param-value>  </context-param>    <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*:config/applicationContext-mvc.xml</param-value>    </init-param>    <load-on-startup>1</load-on-startup>  </servlet>  <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>  <servlet-mapping>    <servlet-name>springMVC</servlet-name>    <url-pattern>/</url-pattern>  </servlet-mapping>  <listener>    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  </listener>  <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

mybaties自动生成配置文件mbg_configuration.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:/mengwx/tanggu/school/WebContent/WEB-INF/lib/mysql-connector-java-5.1.22-bin.jar" />	<context id="mybatisDemoForMysql" targetRuntime="MyBatis3">		<!-- 控制注释 -->		<commentGenerator>			<!-- 是否去除所有自动生成的注释文件 -->			<property name="suppressAllComments" value="true" />			<!-- 是否去除所有自动生成的文件的时间戳,默认为false -->			<property name="suppressDate" value="true" />		</commentGenerator>		<!-- 控制数据库 -->		<jdbcConnection driverClass="com.mysql.jdbc.Driver"			connectionURL="jdbc:mysql://127.0.0.1:3306/wechat?characterEncoding=utf8"			userId="root" password="123456" />		<javaTypeResolver>			<!-- 把jdbc中的decimal与numberic类型转化为java.math.BigDeciaml形式表示 -->			<property name="forceBigDecimals" value="false" />		</javaTypeResolver>		<!-- 数据库表对应的model -->		<javaModelGenerator targetPackage="com.weichu.entiy"			targetProject="src">			<property name="enableSubPackages" value="true" />			<property name="trimStrings" value="true" />		</javaModelGenerator>		<!-- 控制Model的xmlMapper文件 -->		<sqlMapGenerator targetPackage="config.sqlxml"			targetProject="src">			<property name="enableSubPackages" value="true" />		</sqlMapGenerator>		<!-- 控制mapper接口 -->		<javaClientGenerator targetPackage="com.weichu.dao"			type="XMLMAPPER" targetProject="src">			<property name="enableSubPackages" value="true" />			<property name="methodNameCalculator" value="extended" />		</javaClientGenerator>		<!-- schema你的数据库,tableName表明,domainObjectName对应你的javabean类名,是否生成相应的example -->		<!-- <table schema="wechat" tableName="student" domainObjectName="Student"		    enableSelectByPrimaryKey="false"		    enableUpdateByPrimaryKey="false"		    enableDeleteByPrimaryKey="false"			enableCountByExample="false" enableUpdateByExample="false"			enableDeleteByExample="false" enableSelectByExample="false"			selectByExampleQueryId="false">			<generatedKey column="id" sqlStatement="MySql" />			<columnOverride column="name" property="visitor_name" />			<ignoreColumn column="status" delimitedColumnName="false" />					</table> -->				<!-- schema你的数据库,tableName表明,domainObjectName对应你的javabean类名,是否生成相应的example -->		 <table schema="wechat" tableName="test" domainObjectName="Test"		    enableSelectByPrimaryKey="true"		    enableUpdateByPrimaryKey="true"		    enableDeleteByPrimaryKey="true"			enableCountByExample="false" enableUpdateByExample="false"			enableDeleteByExample="false" enableSelectByExample="false"			selectByExampleQueryId="false">			<generatedKey column="id" sqlStatement="MySql" />			<columnOverride column="name" property="name" />			<ignoreColumn column="status" delimitedColumnName="false" />					</table> 	</context></generatorConfiguration>代码生成代码
import java.io.File;import java.io.IOException;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import org.mybatis.generator.api.MyBatisGenerator;import org.mybatis.generator.config.Configuration;import org.mybatis.generator.config.xml.ConfigurationParser;import org.mybatis.generator.exception.InvalidConfigurationException;import org.mybatis.generator.exception.XMLParserException;import org.mybatis.generator.internal.DefaultShellCallback;public class MainFunction {	public static void main(String[] args) {		generateMbgConfiguration();			}	private static void generateMbgConfiguration() {				List<String> warnings = new ArrayList<String>();		boolean overwrite = true;		File configFile = new File("C:/Users/huxf/workspace/weichu/src/config/mbg_configuration.xml");		ConfigurationParser cp = new ConfigurationParser(warnings);		Configuration config = null;		try {			config = cp.parseConfiguration(configFile);		} catch (IOException e) {			// TODO Auto-generated catch block			e.printStackTrace();		} catch (XMLParserException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}		DefaultShellCallback callback = new DefaultShellCallback(overwrite);		try {			MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);			myBatisGenerator.generate(null);		} catch (InvalidConfigurationException e) {			// TODO Auto-generated catch block			e.printStackTrace();		} catch (SQLException e) {			// TODO Auto-generated catch block			e.printStackTrace();		} catch (IOException e) {			// TODO Auto-generated catch block			e.printStackTrace();		} catch (InterruptedException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}		System.out.println("Mybatis接口生成");	}}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表