SpringMVC整合mybatis實例代碼。本站提示廣大學習愛好者:(SpringMVC整合mybatis實例代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是SpringMVC整合mybatis實例代碼正文
MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷徙到了谷歌 code,而且更名為MyBatis 。
1、逆向工程生成基本信息
<?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> <context id="testTables" targetRuntime="MyBatis3"> <commentGenerator> <!-- 能否去除主動生成的正文 true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--數據庫銜接的信息:驅動類、銜接地址、用戶名、暗碼 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3307/mybatis" userId="root" password="jalja"> </jdbcConnection> <!-- 默許false,把JDBC DECIMAL 和 NUMERIC 類型解析為 Integer,為 true時把JDBC DECIMAL 和 NUMERIC 類型解析為java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- targetProject:生成PO類的地位 --> <javaModelGenerator targetPackage="com.jalja.springmvc_mybatis.model.pojo" targetProject=".\src"> <!-- enableSubPackages:能否讓schema作為包的後綴 --> <property name="enableSubPackages" value="false" /> <!-- 從數據庫前往的值被清算前後的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- targetProject:mapper映照文件生成的地位 --> <sqlMapGenerator targetPackage="com.jalja.springmvc_mybatis.mapper" targetProject=".\src"> <!-- enableSubPackages:能否讓schema作為包的後綴 --> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- targetPackage:mapper接口生成的地位 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.jalja.springmvc_mybatis.mapper" targetProject=".\src"> <!-- enableSubPackages:能否讓schema作為包的後綴 --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 指定命據庫表 --> <table tableName="items"></table> <table tableName="orders"></table> <table tableName="orderdetail"></table> <table tableName="user"></table> </context> </generatorConfiguration> public static void main(String[] arhs) throws Exception{ List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("src.main.resources/generator.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); }
2、springMVC與Mybatis整合 各個設置裝備擺設文件
1.項目構造
2、各個文件的焦點代碼
a.web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="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
<?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: setting(全局設置裝備擺設參數設置裝備擺設):mybatis運轉時可以調劑一些運轉參數 例如:開啟二級緩存、開啟延遲加載 typeAliases(類型別號): 在mapper.xml中界說parameterType 參數類型 resultType 前往類型時 須要指定類型的途徑 不便利開辟,我們開一針對 這些類型給其指定別號 typeHandler(類型處置器):在mybatis 中是經由過程typeHandler 完成 jdbc類型與java類型的轉化 ,mybatis 供給的處置器已可知足 開辟需求 objectFactory(對象工場): plugins(插件): environments(情況聚集屬性對象): environment(情況子屬性對象): transactionManager(事務治理): dataSource(數據源): mappers(映照器): --> <!-- 對事務的治理和銜接池的設置裝備擺設 --> <!-- 延遲加載 --> <settings> <!-- 翻開延遲加載 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 積極加載改成消極加載 --> <setting name="aggressiveLazyLoading" value="false"/> <!-- 開啟二級緩存 --> <setting name="cacheEnabled" value="true"/> </settings> <typeAliases> <!-- 針對單個體名界說 --> <!-- <typeAlias type="com.jalja.myBatis.model.User" alias="user"/> --> <!--批量別號的界說 mybatis 主動掃描包中的類 別號就是類名(首字母年夜小寫都可以) --> <package name="com.jalja.springmvc_mybatis.model.pojo"/> <package name="com.jalja.springmvc_mybatis.model.custom"/> <package name="com.jalja.springmvc_mybatis.model.vo"/> </typeAliases> <!--加載映照文件 --> <!-- <mappers> <mapper resource="com/jalja/spring_mybatis/mapper/UserMapper.xml"/> --> <!-- 和spring整合後 可以去失落 <package name="com.jalja.spring_mybatis.mapper"/> </mappers>--> </configuration>
c、config/spring/applicationContext-dao.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="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-placeholder location="classpath:jdbc.properties"/> <!-- 對JDBC設置裝備擺設停止解密 <bean id="propertyConfigurer" class="cn.com.sinobpo.project.wfjb.utils.EncryptablePropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:resources/config/jdbc.properties</value> </list> </property> </bean> --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName"> <value>${jdbc_driverClassName}</value> </property> <property name="url"> <value>${jdbc_url}</value> </property> <property name="username"> <value>${jdbc_username}</value> </property> <property name="password"> <value>${jdbc_password}</value> </property> <!-- 銜接池最年夜應用銜接數 --> <property name="maxActive"> <value>20</value> </property> <!-- 初始化銜接年夜小 --> <property name="initialSize"> <value>1</value> </property> <!-- 獲得銜接最年夜期待時光 --> <property name="maxWait"> <value>60000</value> </property> <!-- 銜接池最年夜余暇 --> <property name="maxIdle"> <value>20</value> </property> <!-- 銜接池最小余暇 --> <property name="minIdle"> <value>3</value> </property> <!-- 主動消除無用銜接 --> <property name="removeAbandoned"> <value>true</value> </property> <!-- 消除無用銜接的期待時光 --> <property name="removeAbandonedTimeout"> <value>180</value> </property> <!-- 銜接屬性 --> <property name="connectionProperties"> <value>clientEncoding=UTF-8</value> </property> </bean> <!-- spring和MyBatis完善整合 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis/applicationContext-mybatis.xml"/> </bean> <!--應用 mapper 署理 的方法 mapper掃描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 掃描包途徑 假如須要掃描多個包 ,中央應用半角逗號離隔 --> <property name="basePackage" value="com.jalja.springmvc_mybatis.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!--聲明式 事務治理 應用jdbc的事務治理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 設置裝備擺設事務告訴--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!-- 設置裝備擺設事務的切點,並把事務切點和事務屬性不聯系關系起來AOP --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.jalja.springmvc_mybatis.service.impl.*.*(..))"/> </aop:config> </beans>
d、config/spring/applicationContext-service.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="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"> <bean id="itemsService" class="com.jalja.springmvc_mybatis.service.impl.ItemsServiceImpl"></bean> </beans>
e、config/spring/springmvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="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.DefaultAnnotationHandlerMapping springmvc3.1之前--> <!-- 映照器 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping springmvc3.1今後 --> <!-- 適配器 org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter springmvc3.1之前--> <!-- 適配器 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter springmvc3.1今後 --> <!--設置裝備擺設映照器和 適配器 <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> --> <!-- 開啟注解 映照器和 適配器 這類方法默許加載了許多參數綁定的辦法 例如 json轉換解析器--> <mvc:annotation-driven/> <!-- 設置裝備擺設 Handler <bean class="com.jalja.springmvc_mybatis.controller.UserController"/>--> <!-- 注解 設置裝備擺設 基於組建掃描的方法 --> <context:component-scan base-package="com.jalja.springmvc_mybatis.controller" /> <!-- 設置裝備擺設自界說參數解析器 --> <mvc:annotation-driven conversion-service="conversionService"/> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <list> <!-- 日期類型轉換 --> <bean class="com.jalja.springmvc_mybatis.converter.CustomDateConverter"></bean> </list> </property> </bean> <!-- 全局異常處置器 --> <bean class="com.jalja.springmvc_mybatis.exception.CustomExceptionResolver"/> <!-- 文件上傳 --> <!-- 支撐上傳文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 文件年夜小 5M --> <property name="maxUploadSize" value="5242880"/> </bean> <!-- 應用 restFul 作風 編程 照成 的 靜態資本 拜訪 成績 --> <!-- <mvc:resources mapping="/js/**" location="/resources/js/"/> --> <!-- springMVC攔阻器的設置裝備擺設 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**" /> <bean class="com.jalja.springmvc_mybatis.interceptor.LoginInterceptor" /> </mvc:interceptor> </mvc:interceptors> <!-- 視圖映照 jsp解析 默許應用jstl--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 默許應用 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="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
package com.jalja.springmvc_mybatis.controller; import java.io.File; import java.util.List; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.jalja.springmvc_mybatis.exception.CustomException; import com.jalja.springmvc_mybatis.model.custom.ItemsCustom; import com.jalja.springmvc_mybatis.service.ItemsService; /** * 商品 * @author PC003 *conterver參數轉換器 springMvc供給了許多參數轉換器 */ @Controller @RequestMapping("/items") //窄化要求映照 public class ItemsController { @Autowired ItemsService itemsService; @RequestMapping(value="/findItemsList") public String findItemsList(Model model) throws Exception{ 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:設置默許值 public String editItems(Model model, @RequestParam(value="id",required=true,defaultValue="0") Integer itemsId) throws Exception{ ItemsCustom itemsCustom=itemsService.findItemsById(itemsId); if(itemsCustom==null){ throw new CustomException("商品不存在"); } model.addAttribute("itemsCustom", itemsCustom); return "editItems"; } @RequestMapping(value="/updateItems") public String editItemsSubmit(Integer id,ItemsCustom itemsCustom,MultipartFile itemsPic) throws Exception{ String uploadFileName=itemsPic.getOriginalFilename();//獲得上傳的文件名 if(itemsPic!=null && uploadFileName!=null && !uploadFileName.equals("")){ String imagesPath="E:\\develop\\upload\\images\\"; String newFileName=UUID.randomUUID()+uploadFileName.substring(uploadFileName.lastIndexOf("."),uploadFileName.length()); File newFile=new File(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 @ResponseBody ItemsCustom jsonRequest(@RequestBody ItemsCustom itemsCustom) throws Exception{ return itemsCustom; } //RestFul 作風 編程 /restFulRequest/{id}:表現將這個地位的參數傳到 @PathVariable 指定的稱號中 @RequestMapping(value="/restFulRequest/{id}") public @ResponseBody ItemsCustom restFulRequest(@PathVariable("id") Integer id) throws Exception{ ItemsCustom itemsCustom=itemsService.findItemsById(id); return itemsCustom; } }
以上所述是小編給年夜家引見的SpringMVC整合mybatis實例代碼,願望對年夜家有所贊助,假如年夜家想懂得更多資訊敬請存眷網站!