Mybatis는 Apache의 오픈 소스 프로젝트입니다. 2010 년 에이 프로젝트는 Apache Software Foundation에서 Google 코드로 이전되었으며 Mybatis로 이름이 바뀌 었습니다.
1. 역 엔지니어링은 기본 정보를 생성합니다
<? xml 버전 = "1.0"encoding = "utf-8"?> <! doctype generatorconfigurationpublic "-// mybatis.org//dtd mybatis 생성기 구성 1.0 // en ""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd "> <GeneratorConfiguration> <context id ="testTables "targetRuntime ="myBatis3 "> <commentGenerator> <!-자동 기준 댓글을 제거 할 것인지 :> no-> <" " value = "true"/> </commentgenerator> <!-데이터베이스 연결 정보 : 드라이버 클래스, 연결 주소, 사용자 이름, 암호-> <jdbcconnection driver class = "com.mysql.jdbc.driver"connectuerl = "jdbc : mysql : // localhost : 3307/mybatis" userId = "root"password = "jalja"> </jdbcconnection> <!-기본 거짓, jdbc 소수 및 숫자 유형을 정수로 구문 분석하고, true, jdbc 소수점 및 숫자 유형은 java.math.bigdecimal-> <javatyperesolver>로 해결됩니다. /> </javatyperesolver> <!-TargetProject : PO 클래스의 위치-> <javamodelgenerator targetpackage = "com.jalja.springmvc_mybatis.model.pojo"TargetProject = "./ src"> <!-EnablesBackages : Schema가 Schema가 Plightix of the Package인지 여부 이름 = "enablebpackages"value = "false" /> <!-데이터베이스에서 반환 된 값이 정리되기 전후의 공간-> <속성 이름 = "trimstrings"value = "true" /> < /javamodelgenerator> <!-TargetProject : 맵퍼 맵 파일이 생성되는 위치-> <sqlmapgenerator TargetPackage = "com.jalja.springmvc_mybatis.mapper"targetproject = "./ src"> <!-EnablesUbPackages : 스키마가 패키지의 접미사가 될지 여부-> <property name = "enablesubpackages"value = "false"/> </sqlmapgenerater> <! -> <property name = "enablebpackages"value = "false"/> </sqlmapgenerator> <!-targetpackage : 맵퍼 인터페이스 생성 위치-> <javaclientgenerator type = "xmlmapper"targetpackage = "com.jalja.springmvc_mybatis.mapproject". 스키마가 패키지의 접미사가 될지-> <속성 이름 = "enablebpackages"value = "false"/> </javaclientgenerator> <!-데이터베이스 테이블을 지정-> <테이블 tablename = "items"> </table> <table tablename = "orders"> </table> <table> <table> <table> <table> tableName = "user"> </table> </context> </generatorConfiguration> public static void main (string [] arhs)은 예외 {list <string> warnings = new arraylist <string> (); boolean overwrite = true; file configfile = new File ( "src.main.resources/generator.xml"); ConfigurationParser (Warnings); configuration config = cp.parseconfiguration (configfile); defaultshellCallback 콜백 = 새로운 defaultshellCallback (Overwrite); myBatisGenerator myBatisGenerator = 새로운 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/javaeehttp://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 </context-param> <Listener> <Leater-Class> org.springframework.web.context.contextloaderListener </Learter-Class> </Listener> <coundxt-param> <param-name> log4jconfiglocation </param-name> <param-value> classpath : log4j.properties </context-param> <context-param> <Param-name> log4jrefreshinterval </param-name> <param- value> 3000 </param- value> </context-param> <layer> <layer-class.spramframework.web.util.log4jconfiglistener </liater-class> <!-게시물 Garblyble 코드-> <filter> <filter-name> SpringencodingFilter </filter-name> <filter-class> org.springframework.web.filter.characterencodingfilter </filter-param> <param-name> incoding </param-name> <param-name> utf-8 </param- value> </init-param> <init-param> <param-name> forceencoding </param-name> <param-value> true </param-value> </init-param> </filter> <filter-name> springencodingfilter </filter-name> <url-pattern>*. do </url-pattern> 컨트롤러-> <servlet> <servlet-name> springmvc </servlet-name> <servlet-class> org.springframework.web.servlet.dispatcherServlet </servlet-class> <init-param> <!-ContextConfiglocation loads springmvc의 구성 파일 (프로세서 어댑터, mapper)이 default its, default its, the default its. Name-Servlet.xml (springmvc-servlet.xml)-> <param-name> contextConfigLocation </param-name> <param-value> classpath : spring/springmvc.xml </param-value> </init-param> <load-on-startup> </servlet> <servletmapping> <servletmapping> <Servlet-name> springmvc </servlet-name> <!-1, *.do : dispatcherservlet는 *.do2에서 끝나는 모든 액세스를 구문 분석합니다. /: DispatcherServlet은 모든 요청을 구문 분석 (정적 자원 포함)이 구성이 편안한 스타일 URL3을 구현할 수 있습니다./*:이 구성은 결국 JSP 페이지-> <Url-Pattern>*로 전달됩니다. DO </url-pattern> </servlet-mapping> <!-SpringMVC 프론트 렌트 컨트롤러 </servlet> springmvc _r </spring-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> </init-param> </init-param> </init-param> </servlet> <servlet-mapping> <servlet-name> springmvc_rest </servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>-> <session-config> <session-timeout> 30 </session-timeout> </session-config> </webapp>
비. config/mybatis/applicationcontext-mybatis.xml
<? xml version = "1.0"alcoding = "utf-8"?> <! doctype configuration public "-// mybatis.org//dtd config 3.0 // en" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-각각의 특성 (Global Propertion) : 2 차 캐시 활성화, 지연된로드 변형기 (유형 별명) : 매개 변수 유형 파라미터 유형 resulttype를 정의 할 때 유형을 반환 할 때 유형의 경로를 지정해야하며 개발하기 편리하지 않아야합니다. 이러한 유형의 별칭을 지정합니다. TypeHandler : MyBatis에서는 JDBC 유형 및 Java 유형의 변환이 TypeHandler를 통해 완료됩니다. MyBatis가 제공하는 프로세서는 개발 요구 사항을 충족시킬 수 있습니다 : 플러그인 : 환경 (Environments Collection Attribute Object) : Environment (Environments Sub-Attribute Object) : TransactionManager (TransactionManager (Transaction Management)) : DataSource (데이터 소스) : Mapper (Mapper) :> <!-Lazy Loading-> Lazy <! 이름 = "lazyloadingEnabled"value = "true"/> <!-수동적 로딩에 활성화-> <설정 이름 = "AggevivelazyLoading"value = "false"/> <!-"false"/> <!-"cacheenabled"value = "true"/> </settings> <antetealiases>-<typealias의 정의-<typealias- <typealias- <typealias- <typealias- <true "value ="cacheenabled "value ="cacheenabled "value ="cacheenabled "value = type = "com.jalja.mybatis.model.user"alias = "user"/>-> <!-배치 별명의 정의 mybatis 자동 스캔 패키지의 클래스 이름은 클래스 이름입니다 (두 번째 문자 모두 상류 및 소문자에 사용할 수 있음)-> <com.jalja.springmvc_mybatis.model.pojo "/>. name = "com.jalja.springmvc_mybatis.model.custom"/> <package name = "com.jalja.springmvc_mybatis.model.vo"/> </inflealiases> <!-매핑 파일-> <!-<mappers> <mapper resource = "com/jalja/spring_mybatis/mapper/usermapper.xml"/>-> <!-스프링과 통합 후 <package 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/aop" xmlns : "http://www.springframework.org/schema/cache"xmlns : context = "http://www.springframework.org/schema/context"xmlns : mvc = "http://www.spramframwork.org/schema/gramework.org/spramwork.org. xmlns : tx = "http://www.springframework.org/schema/tx"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xsi : skemalocation = "http://www.spremaw.spongramwork.org/orwerk.org http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/sprring-beans-3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.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.xsdhttp://www.springframework.org/schema/cache http://www.spramework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd"><! 이름 = "locations"> <str> <alue> classpath : Resources/config/jdbc.properties </value> </list> </property> </bean>-> <bean id = "dataSource"destrop ""close "> <속성 이름 ="driverClassName "> <value> $ {jdbc_driverclassname} </value </property> <property 이름 = "url"> <value> $ {jdbc_url} </value> </property> <property name = "username"> <value> $ {jdbc_username} </value> </property> <property name = "valess"> <value> $ {jdbc_password} </value> <!-<! 이름 = "maxactive"> <value> 20 </value> </propert> <!-연결 크기 초기화-> <속성 이름 = "이니셜 크기"> <value> 1 </value> </property> <!-연결의 최대 대기 시간을 얻습니다-> <속성 이름 = "maxwait"> <value> 60000 </value> </property> <!-최대 공매도 풀-> <Property 이름 = "maxidle"> <value> 20 </value> </propert> <!-최소 유휴 연결 풀-> <속성 이름 = "minidle"> <alue> 3 </value> </property> <!-자동으로 쓸모없는 연결-> <속성 이름 = "removeaBandon"> <value> value> </value> <! 이름 = "removeaBandOnedTimeout"> <value> 180 </value> </property> <!-연결 속성-> <속성 이름 = "ConnectionProperties"> <connectionProperties "> <conceptionProperties"> <conceptionProperties "> <balue> ClientEncoding = utf-8 </value> </property> </bean> <!-<Bean id ="sqlsessionseforce "> <sqlsessiontorforce"> ref = "dataSource"/> <property name = "configlocation"value = "classpath : mybatis/applicationcontext-mybatis.xml"/> </bean> <!-맵퍼 스캐너-> <bean> <!-여러 패키지를 스캔 해야하는 경우 패키지 경로를 스캔하여 반 넓은 쉼표를 사용하여 분리하십시오. value = "com.jalja.springmvc_mybatis.mapper"/> <property name = "sqlsessionfactorybeanname"value = "sqlsessionfactory"/> </bean> <!-선언적 트랜잭션 관리 트랜잭션 관리 jdbc-> <bean id = "transactionManager"> ref = "dataSource"> </property> </bean> <!--트랜잭션 알림 구성-> <tx : 조언 ID = "txAdVice"transaction-manager = "transactionManager"> <tx : attributes> <tx : method name = "update*"propgation = "required"/> <tx : method name = "provagation ="tropagation = "the method name"/>. 전파 = "필수"/> <tx : 메소드 이름 = "get*"propagation = "supports"read-doly = "true"/<tx : 메소드 이름 = "find*"propagation = "supports"read-do = "true"/<tx : attributes> </tx : 조정>-조정 포인트-인트 론적 트랜잭션 지점과 관련이 없습니다. -> <aop : config> <aop : Advisor Advice-Ref = "txadvice"pointcut = "execution (*com.jalja.springmvc_mybatis.service.impl.* 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/aop" xmlns : "http://www.springframework.org/schema/cache"xmlns : context = "http://www.springframework.org/schema/context"xmlns : mvc = "http://www.spramframwork.org/schema/gramework.org/spramwork.org. xmlns : tx = "http://www.springframework.org/schema/tx"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xsi : skemalocation = "http://www.spremaw.spongramwork.org/orwerk.org http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/sprring-beans-3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.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.xsdhttp://www.springframework.org/schema/cache http://www.spramework.org/schema/cache/spring-cache-3.2 id = "항목 서비스"> </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/aop" xmlns : "http://www.springframework.org/schema/cache"xmlns : context = "http://www.springframework.org/schema/context"xmlns : mvc = "http://www.spramframwork.org/schema/gramework.org/spramwork.org. xmlns : tx = "http://www.springframework.org/schema/tx"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xsi : skemalocation = "http://www.spremaw.spongramwork.org/orwerk.org http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/sprring-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.xsdhttp://www.springframework.org/schema/cache http://www.spramework.org/schema/cema/spring-cache-3.xsd">! Mapper-> <!-Mapper org.springframework.web.servlet.mvc.annotation.defaultannotation HandlerMpapp SpringMvc3.1-> <!-Mapper org.springframework.web.servlet.mvc.annotation.defaultannotation handlermpapping springmvc3.1-> <-mapper. org.springframework.web.servlet.mvc.method.annotation.requestmappinghandlermpapping springmvc3.1 이후-> <!-Adapter org.springframework.web.servlet.mvc.annotation.annotationmethhandleradapter springmvc3.1-> adapter. org.springframework.web.servlet.mvc.method.annotation.requestmappinghandleradapter springmvc3.1-> <!-맵퍼 및 어댑터를 구성 <bean/> <bean/>-> <!-주석 맵퍼 및 어댑터를 켜십시오. 이 메소드는 기본적으로 JSON 변환 파서-> <mvc : 주석 구동/> <!-구성 <bean/>-> <!-주석 구성 구성을 기반으로하는 핸들러 구성-> <context : com.jalja.springmvc_ mytroller. 사용자 정의 매개 변수 파서-> <mvc : 주석 중심 변환 서비스 서비스 = "ConversionService"/> <bean id = "ConversionService"> <property name = "converters"> <list> <!-날짜 유형 변환-> </bean> </bean> </bean> </bean> </bean> </bean> <bean/> <!-file up-up-up-uplog. -> <bean id = "multipartresolver"> <!-파일 크기 5m-> <속성 이름 = "maxUploadsize"value = "5242880"/> </bean> <!-RESTFul Style을 사용하여 프로그래밍하여 발생하는 정적 리소스 액세스 문제-<mvc : resources mapping = "/js/**"location = "/js/"->->->->->->-/"/js/. 구성-> <mvc : interceptors> <mvc : interceptor> <mvc : 맵핑 경로 = "/**"/> <bean/> </mvc : interceptor> </mvc : interceptors> <!-VIE VIVE jsp parsing은 jstl-> <ean> <!-기본적 사용 --> view name = "View Class"를 사용합니다. value = "org.springframework.web.servlet.view.jstlview"/> <property name = "prefix"value = "/web-inf/jsp/"/> <property name = "접미사"value = ". jsp"/> </bean> </beans>
f, config/jdbc.properties
jdbc_driverclassname = com.mysql.jdbc.driverjdbc_url = jdbc : mysql : // localhost : 3306/mybatis? useunicode = true & characterencoding = utf-8jdbc_username = rootjdbc_password = 111111
g, config/log4j.properties
#개발 환경에서 로그 레벨을 디버그로 설정해야하며 생성 환경은 정보 또는 ERRORLOG4J.ROOTLOGGER = DEBUG로 설정해야합니다. stdoutlog4j.logger.org.apache.ibatis = debuglog4j.appender.stdout = org.apache.log4j.consoleAppenderlog4j.appender.stdout.layout = org.apache.log4j.patternlayoutlog4j.appender.stdout.layout.convernovernvernvernvers.convernvers.convernvers.convernvers.convernover.layout.layver.convernver.conpathout.conver.conpathout.log4j.patternlayoutlog4j.appender.stdout. %m %n
H, com/jalja/springmvc_mybatis/controller/itemscontroller.java
패키지 com.jalja.springmvc_mybatis.controller; import java.io.file; import java.util.list; import java.util.uuid; import org.spramframework.beans.annotation.AntOWERED; import org.sprameframework.stereotyp.controller; org.springframework.ui.model; import org.springframework.web.bind.annotation.pathvariable; import org.springframework.web.bind.annotation.requestbody; import org.spramframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestmethod; import org.sprameframework.web.bind.annotation.requestparam; import org.spramframework.web.bind.annotation.responsebody; import org.springframework.web.multiptile com.jalja.springmvc_mybatis.exception.customexception; import com.jalja.springmvc_mybatis.model.custom.itemscustom; import com.jalja.springmvc_mybatis.service.iteremservice; 매개 변수 변환기*/@controller@requestmapping ( "/items") // 좁은 요청 매핑 공개 클래스 itemscontroller {@autowired itemservice itemservice; @requestmapping (value = "/finditemslist") public string finditemslist (모델) {list <initemcustom> itemsList = itemsService.FindItemSlist (null); System.out.println (itemsList); model.AdDattribute ( "itemsList", itemsList); return "itemsList";}@retureMapping (value = "/edititems", wither = {retureMethod.post, requestMethod.get}) // 공식 매개 변수가 필요한 매개 변수 : 속성의 값이 기본값으로 전달되어야하도록 지정하십시오. 기본값 공개 문자열 편집 (모델 모델, @requestparam (value = "id", required = true, defaultValue = "0") integer exception {itemscustom itemscustom = itemsservice.finditemsbyid (itemsid); if (itemscustom = null) {새로운 customexception ( "제품이 존재하지 않는다");} model.addattribute ( "itemscustom", itemscustom); return "}@requestmapping (value ="/updateitems ") public editems (integer ed, integer editems). itemsCustom, multipartfile itempic) 예외 {string uploadfilename = itemspic.getoriginalfilename (); // 업로드 된 파일 이름을 가져옵니다. if (itemspic! = null && uploadfilename! = null &&! uploadfilename.equals ( "") {string imagePath = "; newFilename = uuid.randomuuid ()+uploadfilename.substring (uploadfilename.lastindexof ( "), uploadfilename.length ()); file newfile = newfile = newfile (imagespath+newfilename); itemspic.transferto (newfile); itemscustom.setpic (newfilename);} itemsservice.updateItemsByid (id, itemscustom); "리디렉션 : findItemsList.do"; // retirect} // JSON @ResponseBody 사용 : JSON에 객체 @RequestBody : java 객체 @RequestMapping (value = "/jsonRequest")에 따라 json requestCustom jsonrequest (@requestbody itemscustom itemscustom) 예외 {} // Restful Style; 프로그래밍/RESTFULREQUEST/{id} :이 위치의 매개 변수를 @PathVariable @RequestMapping (value = "/retfulRequest/{id}")로 지정된 이름으로 전달하는 것을 의미합니다. public @ResponseBody itemsCustom retfulRequest (@PathVariable ( "id") Integer ID) 예외 {airestcustom experce itemsCustom = itemsService.FindItemsByID (ID); 반환 ItemsCustom;}}}위는 편집자가 소개 한 SpringMVC 통합 MyBatis 예제 코드입니다. 나는 그것이 당신에게 도움이되기를 바랍니다. 더 많은 정보를 알고 싶다면 Wulin.com 웹 사이트에주의를 기울이십시오!