MyBatisはApacheのオープンソースプロジェクトです。 2010年、このプロジェクトはApache Software FoundationからGoogleコードに移動し、MyBatisと改名されました。
1.リバースエンジニアリングは基本情報を生成します
<?xml version = "1.0" encoding = "utf-8"?> <!doctype generatorconfigurationpublic " - // mybatis.org//dtd mybatisジェネレーター構成1.0 // en" "http://mybatis.org/dtd/mybatis-generator-config_1_0 id = "testables" targetruntime = "mybatis3"> <commentgenerator> <! - 自動生成コメントを削除するかどうか真:はい:false:いいえ - > <プロパティ名= "suppressallcomments" value = "true" /> < /commentgenerator> < driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3307/mybatis" userId="root"password="jalja"></jdbcConnection><!-- Default false, parse the JDBC DECIMAL and NUMERIC types into Integer, and when true, JDBC DECIMAL and NUMERIC Type resolves to java.math.bigdecimal-> <javatyperesolver> <プロパティ名= "forcebigdecimals" value = "false" /> < /javatyperesolver> < /javatyperesolver> <! - ターゲットプロジェクト:生成されたPOクラスの場所 - > <javamodelgenerator TargetPackage = "com.jalja.springmvc_mybatis.model.pojo" targetproject = "./ src"> <! - enableSubpackages:schemaをパッケージのサフィックスにするかどうか - > <プロパティ名= "enableSubpackages" value = "fals" name = "trimstrings" value = "true"/> </javamodelgenerator> <! - mapperマップファイルが生成される場所 - > <sqlmapgenerator targetpackage = "com.jalja.springmvc_mybatis.mapper" targetprojed = "パッケージ - > <プロパティname = "enablesubpackages" value = "false" /> < /sqlmapgenerator> <! - enableSubpackages:schemaをパッケージの接尾辞にするかどうか - > <プロパティname = "enableSubpackages" value = "false" /> < /sqlmapgenerator> <! type = "xmlmapper" targetpackage = "com.jalja.springmvc_mybatis.mapper" targetproject = "./ src"> <! - enableSubpackages:スキーマをパッケージの接尾辞にするかどうか - > <プロパティname = "enableasubpass"テーブル - > <テーブルTableName = "items"> </table> <table tablename = "orders"> </table tablename = "orderdetail"> </table> <table tablename = "user"> </table> </context> </generatorconfiguration> public static void main(String> <String <String <上書き= true; file configfile = new file( "src.main.resources/generator.xml"); configurationparser cp = new ConfigurationParser(警告); configuration Config = cp.parseconfiguration(configfile); defallyshellcallback callback = new defallocallator(newwrite(overwrite); mybatisgenerator mybatisgenerator(config、callback、warnings); mybatisgenerator.generate(null);}
2。SpringMVCとMyBatisは、さまざまな構成ファイルを統合します
1。プロジェクト構造
2。各ファイルのコアコード
A.web.xml
<?xmlバージョン= "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> <Welcome-File> index.jsp </welcome-file> </welcome-file-list> <context-param> <param-name> contextconfiglocation </param-name> <param-value> classpath:spring/applicationcontext-* <リスナークラス> org.springframework.web.context.contextloaderlistener </ristener-class> </ristener> <context-param> <param-name> log4jconfiglocation </param-name> <param-value> classpath:log4j.properties </param-> < <param-name> log4jrefreshinterval </param-name> <param-value> 3000 </param-value> </context-param> <リスナー> <リスナー> <リスナークラス> org.springframework.web.util.log4jconfiglistener </リスナークラス> </リスナー<!コード - > <filter> <filter-name> springencodingfilter </filter-name> <filter-class> org.springframework.web.filter.charaCterencodingfilter </filter-class> <init-name>エンコーディング</param-name> <param-value> utf-8 </param-value> </init-param> <init-param> <param-name> counceconding </param-name> <param-value> true </param-value> </init-param> </filter> <filter-mapping> <filter-name> springEncodingfilter </filter-name> <url-pattern>* <servlet-name> springmvc </servlet-name> <servlet-class> org.springframework.web.servlet.dispatcherservlet </servet-class> <init-param> <! - contextconfiglocation loads springconfiglocation loads springconfiglocation loads springmvcの構成ファイル(プロセッサアダプター、マッパー) name-servlet.xml(springmvc-servlet.xml) - > <param-name> contextconfiglocation </param-name> <param-value> classpath:spring/springmvc.xml </init-param> <load-on-startup> 1 </load-on-mapping> <servlet-name> springmvc </servlet-name> <! - 1、 *.do:dispatcherservletは、 *.do2で終了するすべてのアクセスを解析します。 /:DispatcherServletはすべてのリクエスト(静的リソースを含む)を解析するこの構成は、RestfulスタイルのURL3を実装できます/*:この構成は最終的にJSPページに転送されます - > <url-Pattern>*。 <Servet-Class> org.springframework.web.servlet.dispatcherservlet </servet-class> <init-param> <param-name> contextconfiglocation </param-name> <param-value> classpath:spring/applicationcontext-springmvc.xml </param-value> </init-param> <load-param> </servlet> <servlet-mapping> <servlet-name> springmvc_rest </servlet-name> <url-pattern>/</url-pattern> </servet-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構成public " - // mybatis.org//dtd config 3.0 // en" "http://mybatis.org/dtd/mybatis-3-config.dtd"次のようなMyBatisが実行されるときに調整されます:セカンダリキャッシュを有効にし、遅延荷重型型ease(タイプエイリアス):parametertypeパラメータータイプのresulttypeをmapper.xmlで定義します。タイプを返すときは、タイプのパスを指定する必要があります。これらのタイプのエイリアスを指定します。 TypeHandler:MyBatisでは、JDBCタイプとJavaタイプの変換がTypeHandlerによって完了します。 MyBatisが提供するプロセッサは、開発要件を満たすことができますオブジェクトファクター:プラグイン:環境(環境コレクション属性オブジェクト):環境(環境サブアトリビングオブジェクト):トランザクションマネージャー(トランザクション管理):DataSource(データソース):マッパー(マッパー): - > <! name = "lazyloadingEnabled" value = "true"/> <! - アクティブロードへのアクティブロード - > <name = "agressivelazyloading" value = "false"/> <! - enableレベル2キャッシュ - > <"cacheenabled" value = "true"/> </settings> <typealias> <> <> <> <> <> < type = "com.jalja.mybatis.model.user" alias = "user"/> - > <! - バッチエイリアスMybatisの定義Mybatis自動スキャンパッケージのクラス名はクラス名(上下の場合は両方とも使用できます) - > <パッケージ名= " name = "com.jalja.springmvc_mybatis.model.custom"/> <package name = "com.jalja.springmvc_mybatis.model.vo"/> </typealiase> <!リソース= "com/jalja/spring_mybatis/mapper/usermapper.xml"/> - > <! - springと統合した後、<パッケージ名= "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.sp ringframework.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/20 01/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/ 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.xsdhttp://www.springframework.org/schema/cache http://www.springframework/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">< !-- JDBC構成ファイルの紹介 - > <コンテキスト:プロパティパスホルダー場所= "クラスパス:JDBC.Properties"/>> < name = "locations"> <list> <value> classpath:resources/config/jdbc.properties </value> </list> </property> </bean> - > <bean id = "dataSource" Destroy-method = "close"> <property name = "driverclassname"> <value> $ {JDBC_DRIVERCLASSCHNAME> name = "url"> <value> $ {jdbc_url} </value> </property> <property name = "username"> <value> $ {jdbc_username} </value> </property> <property name = "password"> <値> $ {jdbc_password} < name = "maxactive"> <value> 20 </value> </property> <! - 接続サイズの初期化 - > <プロパティ名= "Intialsize"> <value> 1 </value> </property> <! - 接続の最大待機時間を取得 - > <プロパティ名= "maxwait"> <value> 60000 </value> name = "maxidle"> <value> 20 </value> </property> <! - 最小アイドル接続プール - > <プロパティ名= "minidle"> <value> 3 </value> </property> </< name = "RemoveabandonedTimeout"> <value> 180 </value> </property> <! - connectionプロパティ - > <プロパティ名= "ConnectionProperties"> <value> clientEncoding = utf-8 </value> </bean> < ref = "dataSource"/> <プロパティ名= "configlocation" value = "classpath:mybatis/applicationcontext-mybatis.xml"/> </bean> <! - mapper scanner-> <bean> <! - 複数のパッケージをスキャンする必要がある場合はパッケージパスをスキャンします。 value = "com.jalja.springmvc_mybatis.mapper"/> <Property name = "sqlsessionfactorybeanname" value = "sqlsessionfactory"/> </bean> <! - JDBCを使用した宣言的なトランザクション管理トランザクション管理管理ref = "dataSource"> </property> </bean> <! - トランザクション通知の構成 - > <tx:アドバイスid = "txadvice" transaction-manager = "transactionmanager"> <tx:属性> <tx:method name = "update*" propagation = "" rebuly "/> <tx:" save*"save*" "" propagation = "必須"/> <tx:method name = "get*" propagation = "" read-only = "true"/> <tx:method name = "find*" cropagation = "support" 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.sp ringframework.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/20 01/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/ 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.xsdhttp://www.springframework.org/schema/cache http://www.springframework/ id = "itemsservice"> </bean> </bean>
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.sp ringframework.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/20 01/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/ 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/プロセッサマッパー - > <! - mapper org.springframework.web.servlet.mvc.annotation.defaultannotationhandlermapping springmvc3.1-> <! - mapper org.springframework.web.servlet.mvc.annotation.defaultation.defaultationhandlermping springmvc3.1-> <! org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlermapping springmvc3.1 aby> <! - adapter org.springframework.web.servlet.mvc.annotation.annotation.AnnotationMethodhandLeradapter SpringMVC3.1-> <! org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter後のspringmvc3.1-> <! - mapper and adapter <bean/> <bean/> - > <! - 注釈マッパーとアダプターをオンにします。このメソッドは、JSON変換パーサー - > <MVC:Annotation-Driven/> <! - Handler <Bean/> - > <! - Annotation構成など、JSON変換パーサーなど、多くのパラメーターバインディングメソッドをロードします。パーサー - > <MVC:Annotation-driven Conversion-Service = "ConventionService"/> <Bean Id = "ConversionService"> <プロパティ名= "Converters"> <List> <! - list> <! - bean> </list> </property> </Bean> < <bean id = "multipartresolver"> <! - ファイルサイズ5m - > <プロパティ名= "Maxuploadsize" value = "5242880"/> </bean> <! - Restful Styleを使用したプログラミングに起因する静的リソースアクセス問題 - > <! - <<MVC:MVC: "/JS/JSインターセプター構成 - > <MVC:インターセプター> <MVC:インターセプター> <MVC:マッピングパス= "/**"/> <bean/> </mvc:インターセプター> </mvc:インターセプター> <! value = "org.springframework.web.servlet.view.jstlview"/> <プロパティ名= "prefix" value = "/jsp/"/> <プロパティ名= "suffix" value = "。jsp"/> </bean> </beans>
f、config/jdbc.properties
jdbc_driverclassname = com.mysql.jdbc.driverjdbc_url = jdbc:mysql:// localhost:3306/mybatis?useunicode = true&charatereCoding = 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.patternlayoutlog4j4J.Apptrent.layouttuttuttut. -layoutlutlog4J %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.springframework.beans.factory.annotation.autowired; import org.springframework.stringframework.stringframework.stringframework.stringframework 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; org.springframework.web.bind.annotation.RequestMethod; Import org.springframework.web.bind.annotation.RequestParam; Import org.springframework.web.bind.annotation.AnsponseBody; Import org.springframework.web.web.multipart.multipartfide com.jalja.springmvc_mybatis.except.customexception; Import com.jalja.springmvc_mybatis.model.custom.itemscustom; Import com.jalja.springmvc_mybatis.service.itemsservice;多くのパラメーターコンバーター*/@controller@requestMapping( "/items")//狭いリクエストマッピングパブリッククラスitemsController {@autowired itemsservice itemsservice; @requestmapping(value = "/indItemslist")public string findItemslist(モデルモデル)スロー例外itemslist = itemsService.finditemslist(null); system.out.println(itemslist); model.addattribute( "itemslist"、itemslist); return "itemslist";}@requestmapping(value = "/edititems"、method = {requestmethod.post、requestmeth.get/shtppp pimpppip the hintmeth.pep.pepppip meth.必要な正式なパラメーターを使用した要求パラメーター:属性の値をdefaultValueで渡す必要があることを指定します:デフォルト値パブリック文字列editiTems(モデルモデル、@requestParam(value = "id"、必須= true、defaultvalue = "0")スロー例外{itemscustom itemscustom = itemsservice.finditemsbyid(itemsid); if(itemscustom = null){throw new customexception( "製品は存在しません");} model.addattribute( "itemscustom"、itemscustom); return "editiTems";}@requestmapping(value = "/updateItems")public strings ") itemscustom、multipartfile itemspic)スロー例外{string uploadfilename = itemspic.getoriginalfilename(); //アップロードされたファイル名を取得します(itemspic!= null && uploadfileName!= null &&!uploadfileName.equals( "" "" ""; newFileName = uuid.randomuuid()+uploadfileName.substring(uploadFileName.lastIndexof( "。")、uploadfileName.length()); file newfile = new(ImagesPath+newFileName); itempic.transferto(newfile); itemscustom.setpic(newFileName);} itemsService.updateItemsbyid(id、itemscustom); return "redirect:findItemslist.do"; // redirect} // json @responsebodyの使用:json output @requestbodyにオブジェクトに反対する:javaオブジェクトにパラメーターを要求する@requestmapping(value = "/jsonrequest")public @responsebodyアイテムプログラミング/RESTFULREQUEST/{ID}:この位置のパラメーターを @pathvariable @RequestMapping(value = "/restfulrequest/{id}")Public @responsebody itemscustom restfulRequest( @pathvariable( "id")shrowsection {itemscustom itemscustom = itemsservice.finditemsbyid(id); return itemscustom;}}上記は、編集者が紹介したSpringMVC統合MyBatisの例コードです。それがあなたに役立つことを願っています。詳細情報を知りたい場合は、wulin.comのWebサイトに注意してください!