SpringMVC整合mybatis实例代码
MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apachesoftwarefoundation迁移到了googlecode,并且改名为MyBatis。
一、逆向工程生成基础信息
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEgeneratorConfiguration PUBLIC"-//mybatis.org//DTDMyBatisGeneratorConfiguration1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <contextid="testTables"targetRuntime="MyBatis3"> <commentGenerator> <!--是否去除自动生成的注释true:是:false:否--> <propertyname="suppressAllComments"value="true"/> </commentGenerator> <!--数据库连接的信息:驱动类、连接地址、用户名、密码--> <jdbcConnectiondriverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3307/mybatis"userId="root" password="jalja"> </jdbcConnection> <!--默认false,把JDBCDECIMAL和NUMERIC类型解析为Integer,为true时把JDBCDECIMAL和 NUMERIC类型解析为java.math.BigDecimal--> <javaTypeResolver> <propertyname="forceBigDecimals"value="false"/> </javaTypeResolver> <!--targetProject:生成PO类的位置--> <javaModelGeneratortargetPackage="com.jalja.springmvc_mybatis.model.pojo" targetProject=".\src"> <!--enableSubPackages:是否让schema作为包的后缀--> <propertyname="enableSubPackages"value="false"/> <!--从数据库返回的值被清理前后的空格--> <propertyname="trimStrings"value="true"/> </javaModelGenerator> <!--targetProject:mapper映射文件生成的位置--> <sqlMapGeneratortargetPackage="com.jalja.springmvc_mybatis.mapper" targetProject=".\src"> <!--enableSubPackages:是否让schema作为包的后缀--> <propertyname="enableSubPackages"value="false"/> </sqlMapGenerator> <!--targetPackage:mapper接口生成的位置--> <javaClientGeneratortype="XMLMAPPER" targetPackage="com.jalja.springmvc_mybatis.mapper" targetProject=".\src"> <!--enableSubPackages:是否让schema作为包的后缀--> <propertyname="enableSubPackages"value="false"/> </javaClientGenerator> <!--指定数据库表--> <tabletableName="items"></table> <tabletableName="orders"></table> <tabletableName="orderdetail"></table> <tabletableName="user"></table> </context> </generatorConfiguration> publicstaticvoidmain(String[]arhs)throwsException{ List<String>warnings=newArrayList<String>(); booleanoverwrite=true; FileconfigFile=newFile("src.main.resources/generator.xml"); ConfigurationParsercp=newConfigurationParser(warnings); Configurationconfig=cp.parseConfiguration(configFile); DefaultShellCallbackcallback=newDefaultShellCallback(overwrite); MyBatisGeneratormyBatisGenerator=newMyBatisGenerator(config,callback,warnings); myBatisGenerator.generate(null); }
二、springMVC与Mybatis整合各个配置文件
1.项目结构
2、各个文件的核心代码
a.web.xml
<?xmlversion="1.0"encoding="UTF-8"?> <web-appxmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"version="3.0"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>3000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!--post请求乱码--> <filter> <filter-name>SpringEncodingFilter</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>SpringEncodingFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <!--springMvc前端控制器--> <servlet> <servlet-name>springMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- contextConfigLocation加载springMvc的配置文件(处理器适配器,映射器) 如果不配置默认加载的是/WEB-INF/servlet名称-servlet.xml(springMvc-servlet.xml) --> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMvc</servlet-name> <!-- 1、*.do:DispatcherServlet解析所有*.do结尾的访问 2、/:DispatcherServlet解析所有请求(包括静态资源)这种配置可以实现restful风格的url 3、/*:这种配置最终要转发到一个jsp页面 --> <url-pattern>*.do</url-pattern> </servlet-mapping> <!--springMvc前端控制器RestFul <servlet> <servlet-name>springMvc_rest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext-springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMvc_rest</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> --> <session-config> <session-timeout>30</session-timeout> </session-config> </web-app>
b、config/mybatis/applicationContext-mybatis.xml
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTDConfig3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 各个属性 properties: setting(全局配置参数配置):mybatis运行时可以调整一些运行参数例如:开启二级缓存、开启延迟加载 typeAliases(类型别名):在mapper.xml中定义parameterType参数类型resultType返回类型时 需要指定类型的路径不方便开发,我们开一针对这些类型给其指定别名 typeHandler(类型处理器):在mybatis中是通过typeHandler完成jdbc类型与java类型的转化,mybatis提供的处理器已可满足开发需求 objectFactory(对象工厂): plugins(插件): environments(环境集合属性对象): environment(环境子属性对象): transactionManager(事务管理): dataSource(数据源): mappers(映射器): --> <!--对事务的管理和连接池的配置--> <!--延迟加载--> <settings> <!--打开延迟加载--> <settingname="lazyLoadingEnabled"value="true"/> <!--积极加载改为消极加载--> <settingname="aggressiveLazyLoading"value="false"/> <!--开启二级缓存--> <settingname="cacheEnabled"value="true"/> </settings> <typeAliases> <!--针对单个别名定义--> <!--<typeAliastype="com.jalja.myBatis.model.User"alias="user"/>--> <!--批量别名的定义mybatis自动扫描包中的类别名就是类名(首字母大小写都可以)--> <packagename="com.jalja.springmvc_mybatis.model.pojo"/> <packagename="com.jalja.springmvc_mybatis.model.custom"/> <packagename="com.jalja.springmvc_mybatis.model.vo"/> </typeAliases> <!--加载映射文件--> <!--<mappers><mapperresource="com/jalja/spring_mybatis/mapper/UserMapper.xml"/>--> <!--和spring整合后可以去掉 <packagename="com.jalja.spring_mybatis.mapper"/></mappers>--> </configuration>
c、config/spring/applicationContext-dao.xml
<?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd"> <!--引入jdbc配置文件--> <context:property-placeholderlocation="classpath:jdbc.properties"/> <!--对JDBC配置进行解密 <beanid="propertyConfigurer"class="cn.com.sinobpo.project.wfjb.utils.EncryptablePropertyPlaceholderConfigurer"> <propertyname="locations"> <list> <value>classpath:resources/config/jdbc.properties</value> </list> </property> </bean>--> <beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"> <propertyname="driverClassName"> <value>${jdbc_driverClassName}</value> </property> <propertyname="url"> <value>${jdbc_url}</value> </property> <propertyname="username"> <value>${jdbc_username}</value> </property> <propertyname="password"> <value>${jdbc_password}</value> </property> <!--连接池最大使用连接数--> <propertyname="maxActive"> <value>20</value> </property> <!--初始化连接大小--> <propertyname="initialSize"> <value>1</value> </property> <!--获取连接最大等待时间--> <propertyname="maxWait"> <value>60000</value> </property> <!--连接池最大空闲--> <propertyname="maxIdle"> <value>20</value> </property> <!--连接池最小空闲--> <propertyname="minIdle"> <value>3</value> </property> <!--自动清除无用连接--> <propertyname="removeAbandoned"> <value>true</value> </property> <!--清除无用连接的等待时间--> <propertyname="removeAbandonedTimeout"> <value>180</value> </property> <!--连接属性--> <propertyname="connectionProperties"> <value>clientEncoding=UTF-8</value> </property> </bean> <!--spring和MyBatis完美整合--> <beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"> <propertyname="dataSource"ref="dataSource"/> <propertyname="configLocation"value="classpath:mybatis/applicationContext-mybatis.xml"/> </bean> <!--使用mapper代理的方式mapper扫描器--> <beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--扫描包路径如果需要扫描多个包,中间使用半角逗号隔开--> <propertyname="basePackage"value="com.jalja.springmvc_mybatis.mapper"/> <propertyname="sqlSessionFactoryBeanName"value="sqlSessionFactory"/> </bean> <!--声明式事务管理使用jdbc的事务管理--> <beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <propertyname="dataSource"ref="dataSource"></property> </bean> <!--配置事务通知--> <tx:adviceid="txAdvice"transaction-manager="transactionManager"> <tx:attributes> <tx:methodname="update*"propagation="REQUIRED"/> <tx:methodname="save*"propagation="REQUIRED"/> <tx:methodname="delete*"propagation="REQUIRED"/> <tx:methodname="get*"propagation="SUPPORTS"read-only="true"/> <tx:methodname="find*"propagation="SUPPORTS"read-only="true"/> </tx:attributes> </tx:advice> <!--配置事务的切点,并把事务切点和事务属性不关联起来AOP--> <aop:config> <aop:advisoradvice-ref="txAdvice"pointcut="execution(*com.jalja.springmvc_mybatis.service.impl.*.*(..))"/> </aop:config> </beans>
d、config/spring/applicationContext-service.xml
<?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd"> <beanid="itemsService"class="com.jalja.springmvc_mybatis.service.impl.ItemsServiceImpl"></bean> </beans>
e、config/spring/springmvc.xml
<?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd"> <!--注解处理器映射器--> <!--映射器org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMappingspringmvc3.1以前--> <!--映射器org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMappingspringmvc3.1以后--> <!--适配器org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapterspringmvc3.1以前--> <!--适配器org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapterspringmvc3.1以后--> <!--配置映射器和适配器 <beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> <beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>--> <!--开启注解映射器和适配器这种方式默认加载了很多参数绑定的方法例如json转换解析器--> <mvc:annotation-driven/> <!--配置Handler <beanclass="com.jalja.springmvc_mybatis.controller.UserController"/>--> <!--注解配置基于组建扫描的方式--> <context:component-scanbase-package="com.jalja.springmvc_mybatis.controller"/> <!--配置自定义参数解析器--> <mvc:annotation-drivenconversion-service="conversionService"/> <beanid="conversionService"class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <propertyname="converters"> <list> <!--日期类型转换--> <beanclass="com.jalja.springmvc_mybatis.converter.CustomDateConverter"></bean> </list> </property> </bean> <!--全局异常处理器--> <beanclass="com.jalja.springmvc_mybatis.exception.CustomExceptionResolver"/> <!--文件上传--> <!--支持上传文件--> <beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--文件大小5M--> <propertyname="maxUploadSize"value="5242880"/> </bean> <!--使用restFul风格编程照成的静态资源访问问题--> <!--<mvc:resourcesmapping="/js/**"location="/resources/js/"/>--> <!--springMVC拦截器的配置--> <mvc:interceptors> <mvc:interceptor> <mvc:mappingpath="/**"/> <beanclass="com.jalja.springmvc_mybatis.interceptor.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors> <!--视图映射jsp解析默认使用jstl--> <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--默认使用--> <propertyname="viewClass"value="org.springframework.web.servlet.view.JstlView"/> <propertyname="prefix"value="/WEB-INF/jsp/"/> <propertyname="suffix"value=".jsp"/> </bean> </beans>
f、config/jdbc.properties
jdbc_driverClassName=com.mysql.jdbc.Driver jdbc_url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8 jdbc_username=root jdbc_password=111111
g、config/log4j.properties
#在开发环境下的日志级别要设置成debug,生成环境设置成info或error log4j.rootLogger=debug,stdout log4j.logger.org.apache.ibatis=debug log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p[%t]-%m%n
h、com/jalja/springmvc_mybatis/controller/ItemsController.java
packagecom.jalja.springmvc_mybatis.controller; importjava.io.File; importjava.util.List; importjava.util.UUID; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.stereotype.Controller; importorg.springframework.ui.Model; importorg.springframework.web.bind.annotation.PathVariable; importorg.springframework.web.bind.annotation.RequestBody; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RequestMethod; importorg.springframework.web.bind.annotation.RequestParam; importorg.springframework.web.bind.annotation.ResponseBody; importorg.springframework.web.multipart.MultipartFile; importcom.jalja.springmvc_mybatis.exception.CustomException; importcom.jalja.springmvc_mybatis.model.custom.ItemsCustom; importcom.jalja.springmvc_mybatis.service.ItemsService; /** *商品 *@authorPC003 *conterver参数转换器springMvc提供了很多参数转换器 */ @Controller @RequestMapping("/items")//窄化请求映射 publicclassItemsController{ @AutowiredItemsServiceitemsService; @RequestMapping(value="/findItemsList") publicStringfindItemsList(Modelmodel)throwsException{ List<ItemsCustom>itemsList=itemsService.findItemsList(null); System.out.println(itemsList); model.addAttribute("itemsList",itemsList); return"itemsList"; } @RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET})//限制Http请求方式 //@RequestParam将请求参数与形式参数进行绑定required:指定属性必须传入值defaultValue:设置默认值 publicStringeditItems(Modelmodel,@RequestParam(value="id",required=true,defaultValue="0")IntegeritemsId)throwsException{ ItemsCustomitemsCustom=itemsService.findItemsById(itemsId); if(itemsCustom==null){ thrownewCustomException("商品不存在"); } model.addAttribute("itemsCustom",itemsCustom); return"editItems"; } @RequestMapping(value="/updateItems") publicStringeditItemsSubmit(Integerid,ItemsCustomitemsCustom,MultipartFileitemsPic)throwsException{ StringuploadFileName=itemsPic.getOriginalFilename();//获取上传的文件名 if(itemsPic!=null&&uploadFileName!=null&&!uploadFileName.equals("")){ StringimagesPath="E:\\develop\\upload\\images\\"; StringnewFileName=UUID.randomUUID()+uploadFileName.substring(uploadFileName.lastIndexOf("."),uploadFileName.length()); FilenewFile=newFile(imagesPath+newFileName); itemsPic.transferTo(newFile);//将内存中的数据写入磁盘 itemsCustom.setPic(newFileName); } itemsService.updateItemsById(id,itemsCustom); return"redirect:findItemsList.do";//重定向 } //JSON的使用@ResponseBody:将对像转json输出@RequestBody:将请求参数转java对象 @RequestMapping(value="/jsonRequest") public@ResponseBodyItemsCustomjsonRequest(@RequestBodyItemsCustomitemsCustom)throwsException{ returnitemsCustom; } //RestFul风格编程/restFulRequest/{id}:表示将这个位置的参数传到@PathVariable指定的名称中 @RequestMapping(value="/restFulRequest/{id}") public@ResponseBodyItemsCustomrestFulRequest(@PathVariable("id")Integerid)throwsException{ ItemsCustomitemsCustom=itemsService.findItemsById(id); returnitemsCustom; } }
以上所述是小编给大家介绍的SpringMVC整合mybatis实例代码,希望对大家有所帮助,如果大家想了解更多资讯敬请关注毛票票网站!