Mybatis - это проект с открытым исходным кодом Apache. В 2010 году этот проект был перенесен от Apache Software Foundation в Google Code и был переименован в Mybatis.
1. Обратная техническая инженерия генерирует основную информацию
<? xml version = "1.0" Encoding = "UTF-8"?> <! Doctype GeneratorConfigurationPublic "-// mybatis.org//dtd mybatis Generation Configuration 1.0 // en "" http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd "> <generatorConfiguration> <Контекст ID =" testtables " value = "true"/> </commentgenerator> <!-Информация о подключении базы данных: класс драйвера, адрес подключения, имя пользователя, пароль-> <jdbcconnection driverclass = "com.mysql.jdbc.driver" connectionUrl = "jdbc: mysql: // localhost: 3307/mybatis" userId = "root" password = "jalja"> </jdbcconnection> <!-по умолчанию False, проанализируйте десятичные и числовые типы JDBC в целое число, и когда True, JDBC Decimal и Numeric Type решаются для Java.math.bigdecimal-> <javatyperesolver> <property name = "fistbiGimal" "javatyperesolver> <vilfity name =" fistbiGimal "=" vallyBIMAL "" vallyBIMAL "" vally "=" vallyBIMAL "= valieBIMAL" "javatyperesolver> <vilfybigmal". /> </javatyperesolver> <!-TargetProject: местоположение сгенерированного класса PO-> <javamodelgenerator TargetPackage = "com.jalja.springmvc_mybatis.model.pojo" targetProject = "./ src"> <! name = "enablesBpackages" value = "false" /> <!-Пространства до и после значения, возвращаемого из базы данных, очищаются-> <name = "trimstrings" value = "true" /> < /javamodelgenerator> <!-TargetProj TargetPackage = "com.jalja.springmvc_mybatis.mapper" targetproject = "./ src"> <!-enablesubpackages: чтобы схема была суффиксом пакета-> <свойство = "ensablesubpackages" value = "false"/> </sqlmapgenatortor> <! -> <Property name = "enablesBpackages" value = "false"/> </sqlmapgenerator> <!-TargetPackage: местоположение генерации интерфейса Mapper-> <javaclientgenerator type = "xmlmapper" targetPackage = "jalja.springmvc_mybatis.mapper". enableSubPackages: Whether to let schema be the suffix of the package --><property name="enableSubPackages" value="false" /></javaClientGenerator><!-- Specify database tables--><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 confighe = new File ("src.main.Resources/generator.xml"); ConfigurationParser (предупреждения); конфигурация config = cp.parseconfiguration (configfile); defaultcallcallback callback = new DefaultshellCallback (перезапись); mybatisgenerator mybatisgenerator = new mybatisgenerator (конфигурация, обратный вызов, Warnings); mybatisenerator 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/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" версия = "3.0"> <Welcome-file-list> <selcoven-file> index.jsp </werveding-file> </werveding-file-list> <context-param> <param-name> contextConfiglocation </param-name> <value> classpath: Spring/ApplicationContext-*. xml </param-value> </context-param> <lloader-class> org.springframework.web.context.contextloaderListener </sluster> </alinger> <context-param> <param-name> log4jconfiglocation </param-name> <param-value> classpath: log4j.properties </param-value> </context-param> <param-name> log4jrefreshinterval </param-name> <param-value> 3000 </param-value> </context-param> <delloader> <lisherer-class> org.springframework.web.util.log4jconfiglistener </slirler-class> </slirler> <! Code-> <filter> <filter-name> Springencodingfilter </filter-name> <filter-class> org.springframework.web.filter.characterencodingfilter </filter-class> <init-param> <param-name> кодинг </param-name> <value> utf-8 </param-vale> </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>. Контроллер-> <servlet> <servlet-name> springmvc </servlet-name> <servlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <init-param> <!-ContextConfiglocation Loads нагрузки SpringMV name-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-mapping> <servlet-name> springmvc </servlet-name> <!-1, *.do: DispatcherServlet Sacksse Все доступ, заканчивающиеся в *.do2. /: DispatcherServlet SANESS Все запросы (включая статические ресурсы) Эта конфигурация может реализовать URL3,/*:*: Эта конфигурация в конечном итоге будет направлена на страницу JSP-> <Url-pattern>*. Do </url-pattern> </servlet-mapping> <!-Front-end-контроллер Restler </servlet-name> spreslemv> <! <Servlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <init-param> <param-name> contextConfiglocation </param-name> <value> classPath: Sprup/ApplicationContext-springmvc.xml </param-value> </init-param> <dutd-on-startpc <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>
беременный config/mybatis/ApplicationContext-mybatis.xml
<? xml version = "1.0" Encoding = "UTF-8"?> <! Конфигурация doctype public "-// mybatis.org//dtd config 3.0 // en" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <perifulation> <perifulation. Параметры могут быть скорректированы при запуске Mybatis, например: Включение вторичного кэша, включение задержки нагрузки Typealiases (тип псевдоним): определить параметры параметра параметра в Mapper.xml При возврате типа вам необходимо указать путь типа, и он не удобен для развития. Мы указам псевдоним для этих типов. TypeHandler: в Mybatis преобразование типа JDBC и типа Java завершено через TypeHandler. Процессор, предоставленный Mybatis, может соответствовать требованиям к разработке объект. name = "LazyLoadingEnabled" value = "true"/> <!-Активная загрузка на пассивную загрузку-> <Настройка name = "AggrevessIvelaZyling" value = "false"/> <!-Включить кэш уровня 2-> <Настройка name = "cacheenabled" value = "true"/> </settings> <typealiases> <! Type = "com.jalja.mybatis.model.user" alias = "user"/>-> <!-Определение псевдоним партии mybatis. Имя класса в пакете автоматического сканирования-это имя класса (обе первые буквы могут использоваться для верхнего и нижнего регистра)-> <come = "com.jalja.springmvc_mybatis.model. name = "com.jalja.springmvc_mybatis.model.custom"/> <name = "com.jalja.springmvc_mybatis.model.vo"/> </typealiases> <! resource = "com/jalja/spring_mybatis/mapper/usermapper.xml"/>-> <!-После интеграции с пружиной вы можете удалить <name = "com.jalja.spring_mybatis.mapper"/> </mappers>-> </configuration>
в 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.springframe.orshore. xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlschema-insstance" xsi: schemalocation = "http://www.springema 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-3.2.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.2.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">! name = "locations"> <silect> <datule> classpath: resources/config/jdbc.properties </value> </list> </property> </bean>-> <bean id = "dataSource" destroy-method = "close"> <свойство name = "DriverClassName"> $ {JDBC_DRIVERCLASSNAM name = "url"> <value> $ {jdbc_url} </value> </property> <name = "username"> <value> $ {jdbc_username} </value> </properation> <name = "password"> <value> $ {jdbc_password} </value> </properation> <!-Максимум. name = "maxactive"> <value> 20 </value> </property> <!-Инициализируйте размер соединения-> <name = "initialSize"> <dalue> 1 </value> </property> <!-Получить максимальное время ожидания для соединения-> <Свойство = "maxwait"> <Значение> 60000 </value> </property> <! name = "maxidle"> <dulch> 20 </value> </property> <!-Минимальный пул соединений на холостом ходу-> <name = "minidle"> <value> 3 </value> </property> <!-автоматически очистить бесполезное соединение-> <Свойство имя = "removeaeAdaned"> <value> true </value> </property> <! name = "RemoveAbandOneTimeOut"> <Daga> 180 </value> </property> <!-Свойства соединения-> <name = name = "connectionProperties"> <dulch> clientencoding = utf-8 </value> </property> </bean> <!-Идеальная интеграция Spring и Mybatis-> <Bean Id = "SqlSessionFactory"> "name" name "name"> "name" name ">" namy ">" name ">" name ">" dato name ">" name ">" name ">" datoMy name " ref = "dataSource"/> <name = "configlocation" value = "classPath: mybatis/applicationContext-mybatis.xml"/> </bean> <!-сканер Mapper-> <Bean> <!-сканировать путь пакета, если вам нужно сканировать несколько пакетов, используйте ползубную коммунацию, чтобы отделить их-> <и имя свойства. value = "com.jalja.springmvc_mybatis.mapper"/> <name = "sqlSessionFactoryBeanName" value = "sqlSessionFactory"/> </bean> <!-декларативная транзакция управления транзакциями с использованием jdbc-> <bean id = "TransactionManger"> <собственное имя = "DataSource" ref = "DataSource"> </property> </bean> <!-Настройка уведомления о транзакции-> <TX: Advice ID = "txAdvice" Transaction-Manager = "TransactionManager"> <TX: атрибуты> <TX: Method Name = "update*" Propagation = "требуется"/> <TX: method nameld = "save*propagation ="/"/"/"/> <tx:" save*save*"="/"/"/"/> <tx:" save*save*"=" "/"/"/"/> <tx: "save*save*" = ""/"/"/> <tx: method method name = "save*". Propagation = "trey"/> <tx: method name = "get*" propagation = "Поддерживает" read-only = "true"/> <tx: method name = "find*" Propagation = "Поддерживает" read-only = "true"/> <tx: атрибуты> </tx: советы> <! -> <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.springframe.orshore. xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlschema-insstance" xsi: schemalocation = "http://www.springema 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-3.2.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.2.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd id = "itemsservice"> </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.springframe.orshore. xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlschema-insstance" xsi: schemalocation = "http://www.springema http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-shans-3.0.xssd 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.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2. Mapper-> <!-mapper org.springframework.web.servlet.mvc.annotation.defaultannotationhandlermapping Springmvc3.1-> <!-Mapper org.springframework.web.servlet.mvc.annotation.defaultantationhandpopping. 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-> <!-Настройка Mapper и Adapter <Bean/> <Bean/>-> <!-Поверните карт аннотации и адаптер. Этот метод загружает множество методов привязки параметров по умолчанию, таких как анализатор преобразования JSON-> <MVC: Annotation-управляемая/> <!-Configure Handler <bean/>-> <!-Конфигурация аннотации основана на методе строительства сканирования-> <context: component-scan base-package = "com.jalja.springmvc_mybatis.can-package =" com.jalja.springmvc_mybatis.Contr Parser-> <MVC: Annotation, управляемая конверсии-service = "conversionservice"/> <bean id = "conversionservice"> <name = "converters"> <sist> <!-конверсия типа даты-> <bean> </bean> </list> </propetion> </bean> <!-Global Exception Handler-> <Bean/> <! <bean id = "multiartresolver"> <!-размер файла 5m-> <name = "maxuploadSize" value = "5242880"/> </bean> <!-Статическая проблема доступа к ресурсам, вызванная программированием с использованием Restful Style-> <!-<MVC: MAPPAPION = "/JS/**"/resources/JS/JS/JS/JS/JS/JS/JS/JS/JS/JS/JS/JSMEMEMEMEMEMPER/JS/JSMEM Конфигурация-> <MVC: Interceptors> <MVC: Interceptor> <MVC: mapping path = "/**"/> <bean/> </mvc: receptor> </mvc: Interceptors> <!-View Map jsp parsing jstl-> <bean> <!-defloab value = "org.springframework.web.servlet.view.jstlview"/> <name = "prefix" value = "/web-inf/jsp/"/> <name = "suffix".
f, config/jdbc.properties
jdbc_driverclassname = com.mysql.jdbc.driverjdbc_url = jdbc: mysql: // localhost: 3306/mybatis? useUnicode = true & haremencoding = utf-8jdbc_username = rootjdbc_password = 111111
g, config/log4j.properties
#В среде разработки, уровень журнала должен быть установлен для отладки, среда генерации должна быть установлена на info или errorlog4j.rootlogger = отладка, stdoutlog4j.logger.org.apache.ibatis = debuglog4j.appender.stdout = org.apache.log4j.consoleappenderlog4j.appender.stdout.layout = org.apache.log4j.patternlayoutlog4j.appender.stdou %m %n
h, com/jalja/springmvc_mybatis/controller/itemscontroller.java
Пакет com.jalja.springmvc_mybatis.controller; import java.io.file; импорт java.util.list; import java.util.uuid; импорт org.springframework.beans.factory.annotation.autowired; импорт org.spramework.beantory.controller org.springframework.ui.model; import org.springframework.web.bind.annotation.pathvariable; импорт org.springframework.web.bindtation.requestbody; импорт org.springframework.web.bindatation.requestmapping; org.springframework.web.bind.annotation.requestmethod; импорт org.springframework.web.bind.annotation.requestparam; импорт org.springframework.web.bindtation.responsebody; импорт org.spramework.web.multipart.multipart. com.jalja.springmvc_mybatis.exception.customexception; import com.jalja.springmvc_mybatis.model.custom.itemscustom; импорт com.jalja.springmvc_mybatis.service.itemsservice;/*** Продукт* @@authtor pc003. Конвертеры параметров*/@controller@requestmapping ("/items") // Узкое сопоставление запросов public class epestroller {@autowired itemsservice itemsservice; @requestmapping (value = "/finditemslist") public String finditemslist (модель модели). itemslist = itemssservice.finditemslist (null); System.out.println (itemslist); model.addattribute ("itemslist", itemslist); return "itemsliz Требуемые параметры: укажите, что значение атрибута должно быть передано в DefaultValue: Установите значение по умолчанию public String Edititems (модель модели, @RequestParam (value = "id", обязательно = true, defaultValue = "0") Integer itemsId) throws Exception {itemscustom iscustom = vitessSby.finditemsbyd (itepscustom emestom ebustom = itemscustom = itemscustom isullom. Customexception («Продукт не существует»);} model.addattribute ("itemscustom", itemscustom); return "edititems";}@requestMapping (value = "/updateTems") public String EdititemsSsubmit (integer id, itemscustom epestcustom, multiте uploadfilename = itempic.getoriginalfilename (); // Получить загруженное имя файла if (itempic! = null && uploadfilename! = null &&! uploadfilename.equals ("")) {String Imagespath = "e: // upload // equals/"; newFilename = uuid.randomuuid ()+uploadfilename.substring (uploadfilename.lastindexof ("."), uploadfilename.length ()); файл newfile = new File (imagespath+newfileName); itspic.transferto (newfile); // Написать данные в память о Disk to to itemscustom.setpic (newfilename);} itemsservice.updateItemsbyid (id, itemscustom); return "redirect: finditemslist.do"; // redirect} // Использование json @Responsebody: чтобы возразить против вывода json @requestbody: запросить параметры в java object @requestmapping (value = "/jsonrequest") public @Responsebody itemscustom jsonRequest (@Requestbody itemscustom) trowse {returncustm stipscustm; Программирование/restfulRequest/{id}: это означает передавать параметр в этой позиции с именем, указанным @pathvariable @requestmapping (value = "/restfulrequest/{id}") public @Responsebody itemscustom restfulRequest (@pathvariate ("id") integ itemscustom = itemsservice.finditemsbyid (id); return itemscustom;}}Выше приведено комплекс SpringMVC, интегрированный пример MyBatis, представленный вам редактором. Я надеюсь, что это будет полезно для вас. Если вы хотите узнать больше информации, обратите внимание на веб -сайт wulin.com!