Mybatis adalah proyek open source dari Apache. Pada 2010, proyek ini dipindahkan dari Apache Software Foundation ke Google Code dan berganti nama menjadi Mybatis.
1. Reverse Engineering menghasilkan informasi dasar
<? Xml Version = "1.0" encoding = "UTF-8"?> <! Doctype GeneratorConfigurationPublic "-// 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><!-- Whether to remove the auto-generated comments true: Yes: false: No--><property name="suppressAllComments" value="true" /></commentGenerator><!--Database connection information: driver class, connection address, username, password--><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3307/mybatis" userid = "root" kata sandi = "jalja"> </jdbcconnection> <!-default false, parse tipe desimal dan numerik JDBC menjadi bilangan bulat, dan ketika benar, jdbc desimal dan tipe numerik diselesaikan ke java.math. /> </javatyperesolver> <!-TargetProject: Lokasi kelas PO yang dihasilkan-> <javamodelgenerator targetPackage = "com.jalja.springmvc_mybatis.model.pojo" targetProject = "./ src"> <!-enableSubpackage "targetprox =" ./ src "> <! name = "EnableSubPackages" value = "false" /> <!-Spaces sebelum dan sesudah nilai yang dikembalikan dari database dibersihkan-> <name properti = "trimstrings" value = "true" /> </javamodelgenerator> <!-TargetProject: Di mana file peta mapper dihasilkan-> <sqlmeapgenerator TargetPackage = "com.jalja.springmvc_mybatis.mapper" targetProject = "./ src"> <!-memungkinkan pengemasan: apakah akan membiarkan skema menjadi suffix paket-> <property name = "enableSubpackages" value = "false"/</sqlmapgener dari> apa pun yang ada. -> <name properti = "enableSubpackages" value = "false"/> </sqlmapgenerator> <!-TargetPackage: Lokasi Mapper Interface Generation-> <JavaClientGenerator type = "xmlmapper" targetPackage = "com.jalja.springmvc_mybata.mapper" EnableSubPackages: Apakah akan membiarkan skema menjadi sufiks paket-> <name properti = "enableSubpackages" value = "false"/> </JavaClientGenerator> <!-tentukan tabel basis data-> <tableName = "item"> </tabel> <tableName = "orders"> </tabel> </tabel = "tabel" tabel = "tabel" tabel = "tabel"> </tabel> </tabel> </tabel> </tabel = "tabel"> </tabel> </tabel> </tabel> </tabel> </tabel "> </tabel"> </tabel "> </tabel"> </tabel "> </tabel"> </tabel "> Tablename = "user"> </able> </context> </generatorconfiguration> public static void main (string [] arhs) melempar pengecualian {list <string> warnings = new arraylist <string> (); boolean overwrite = true; file configFile = file baru ("src.main.resources/generor = generator = generor (" src.main. ConfigurationParser(warnings);Configuration config = cp.parseConfiguration(configFile);DefaultShellCallback callback = new DefaultShellCallback(overwrite);MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);myBatisGenerator.generate(null);} 2. SpringMVC dan MyBatis mengintegrasikan berbagai file konfigurasi
1. Struktur Proyek
2. Kode inti dari setiap file
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/javaeeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" Versi = "3.0"> <creendak-file-file> <creendak-file> index.jsp </celcome-file> </celcome-file-list> <Context-param> <param-name> ContextConfigLocation </param-name> <param-value> Classpath: Spring/ApplicationContext-*. Xml </param-Value> <listener-class> org.springframework.web.context.contextLoaderListener </engeaner-class> </engeaner> <param> <param-name> log4jConfigLocation </param-name> <param-value> classpath: log4j.properties </param-name> <param-value> classpath: log4j.properties </param-value> <param-value> classpath: log4j.properties </param-value> <param-value> classpath: log4j.properties </param-value> <value> classpath: LOG4J.properties </param-value> <param-name> log4jrefresherinterval </param-name> <param-value> 3000 </param-value> </context-param> <Distener> <Distener-Class> org.springframework.web.util.log4jconfigListener </listener-class> </listener> <! Kode-> <nilter> <nilter-name> SpringEncodingFilter </tilter-name> <nift-class> org.springframework.web.filter.characterencodingfilter </filter-class> <Ilin-param> <param-name> encoding </param-name> <param-value> UTF-8 </Param-Param- Param- </init-param> <Ilin-param> <param-name> ForceEncoding </param-name> <param-value> true </param-value> </it-param> </filter> <nilter-Mapping> <Tinfter-name> SpringenCodingFilter </filter-name> <riler-pattern>*do </url-Polat> </filter-name> <rull-pattern> <servlet-name>springMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- contextConfigLocation loads springMvc's configuration file (processor adapter, mapper) If not configured, the default loading is /WEB-INF/servlet name-servlet.xml (springmvc-servlet.xml)-> <param-name> contextConfigLocation </param-name> <param-value> classpath: springmvc.xml </param-value> </it-param> <boad-on-startup> </load-on startup> </init-param> <boad-on-startup> 1 </load-on startup> <servlet-name> springmvc </servlet-name> <!-1, *.do: DispatcherServlet Parses Semua akses yang diakhiri dengan *.do2. /: DispatcherServlet Parse semua permintaan (termasuk sumber daya statis) Konfigurasi ini dapat mengimplementasikan URL3 gaya RESTful,/*: Konfigurasi ini pada akhirnya akan diteruskan ke halaman JSP-> <RURL-PATERS>*. Lakukan </rerl-Pattern> </Servlet-Mapping> <!-SpringMVC Front-end Controller RESTFUL </RABLET> </Servlet-Mapping> <! <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-papping> <servlet-name> springmvc_rest </servlet-name> <ritl-pola>/</ruRl-pattern> </servlet-mapping>-> <sesi-config> <sesi-timeout> </sesi-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"> <someetururasi> <someety> Someation: Suatu Someururasi, Someruration: Someruration: Some Parety: Some Paretiurasi: Someetiurasi: Parameter dapat disesuaikan saat mybatis dijalankan, seperti: Aktifkan cache sekunder, aktifkan typealiases pemuatan yang tertunda (tipe alias): Tentukan parameter parameter tipe parameter HasilType di mapper.xml saat mengembalikan tipe, Anda perlu menentukan jalur jenis dan tidak nyaman untuk dikembangkan. Kami akan menentukan alias untuk jenis ini. TypeHandler: Di mybatis, konversi tipe JDBC dan tipe Java diselesaikan melalui TypeHandler. Prosesor yang disediakan oleh MyBatis dapat memenuhi persyaratan pengembangan ObjectFactory: Plugin: Environments (Lingkungan mengoleksi objek atribut): lingkungan (objek sub-atribut lingkungan): TransactionManager (Manajemen Transaksi): DataSource (Sumber Data): Mappers (Mapper):-> <!-Manajemen transaksi dan konfigurasi kumpulan koneksi-> <! name = "LazyLoadingEnabled" value = "true"/> <!-Active Loading ke Pasive Loading-> <pengaturan nama = "agresivelazyLoading" value = "false"/> <!-Mengaktifkan Cache Level 2-> <pengaturan nama = "Cacheenabled" value = "true"/</settings> <settings> <typeaLiases> <! Type = "com.jalja.mybatis.model.user" alias = "user"/>-> <!-Definisi batch alias mybatis Nama kelas dalam paket pemindaian otomatis adalah nama kelas (keduanya "huruf besar dapat digunakan untuk huruf besar dan kecil)-<paket nama =" com.jalja.springmc.mbc.mbc.mba. name = "com.jalja.springmvc_mybatis.model.custom"/> <package name = "com.jalja.springmvc_mybatis.model.vo"/</typealiases> <! resource = "com/jalja/spring_mybatis/mapper/usermapper.xml"/>-> <!-Setelah berintegrasi dengan pegas, Anda dapat menghapus <package name = "com.jalja.spring_mybatis.mapper"/> </pappers>-> </konfigurasi>
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/orga/aPema/http://www.spramework.org/orga/aPema/sphema/www.spramework.org/orga/aPema/aPema/http" xmlns: cache = "http://www.springframework.org/schema/cache" xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http:/schema/context" xmlns: mvc = "http:/schema.cfring. xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalocation = "http: htaMa http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http:/www.spramework.org/schema/beans http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/www.springframework.org/schema/schema/www.springframework.orga/schema/schema 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.xsdhtp://www.springframework.org/schema/cache http://www.spramework.org/schema http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">< !-- memperkenalkan file konfigurasi jdbc-> <konteks: properti-placeHolder lokasi = "classpath: jdbc.properties"/<! Name = "Lokasi"> <cist> <value> classpath: sumber daya/config/jdbc.properties </ value> </list> </propert> </tact>-> <bean id = "DataSource" Destroy-Method = "Tutup"> <Properti Nama = "DriverClassName"> <value> $ {jdbc_driver name = "url"> <value> $ {JDBC_URL} </ value> </property> <Properti name = "userName"> <value> $ {jdbc_username} </ value> </prop Property> </value property> </value </valuume> $ {jdbc_password} </value </value> </value </valuume no PIOPT> $ {jdbc_password} </value </values Name = "MaxActive"> <value> 20 </value> </pruptent> <!-inisialisasi ukuran koneksi-> <name properti = "inisialisasi"> <value> 1 </value> </propert> <!-Dapatkan waktu tunggu maksimum untuk koneksi-> <name properti = "MaxWait"> <value> 60000 </value> </properti Property> <! Name = "MaxIdle"> <value> 20 </value> </propt> <!-Kolam koneksi idle minimum-> <name properti = "Minidle"> <value> 3 </value> </propt> <!-Secara otomatis menghapus koneksi yang tidak berguna-> <nama properti = "RemoveBandoned"> <value> true </value> </property> <!-clear waite for for-value> </value> </value> </property> <! name = "RemoveAbandOndTimeout"> <value> 180 </value> </property> <!-Properti koneksi-> <name properti = "ConnectionProperties"> <value> clientencoding = UTF-8 </value> </property> </bean> <!-Integrasi Sempurna Spring dan MyBatis-> <bean id = "SQ =" SQ = "SQ =" SQ = "SQ =" SQ = "SQ =" SQ = "SQ =" Ref = "DataSource"/> <name properti = "configLocation" value = "classpath: mybatis/applicationContext-mybatis.xml"/> </tacer> <!-pemindai mapper-> <bean> <!-memindai jalur paket jika Anda perlu memindai beberapa paket, menggunakan koma setengah-dua untuk dipisahkan-"Basepe" value="com.jalja.springmvc_mybatis.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- Declarative Transaction Management Transaction Management Using jdbc--><bean id="transactionManager"><property name="dataSource" Ref = "DataSource"> </prop Property> </bean> <!-Mengkonfigurasi pemberitahuan transaksi-> <tx: nasihat id = "txadvice" transaction-manager = "transactionManager"> <tx: atribut> <tx: "save =" update*"propagation =" wajib "/<tx: nama metode =" save*" propagation="REQUIRED"/><tx:method name="get*" propagation="SUPPORTS" read-only="true"/><tx:method name="find*" propagation="SUPPORTS" read-only="true"/><tx:attributes></tx:advice><!-- Configure transaction point-insert and do not associate transaction point-insert with transaction attributes AOP -> <aop: config> <aop: advisor nasihat-ref = "txadvice" pointcut = "eksekusi (*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/orga/aPema/http://www.spramework.org/orga/aPema/sphema/www.spramework.org/orga/aPema/aPema/http" xmlns: cache = "http://www.springframework.org/schema/cache" xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http:/schema/context" xmlns: mvc = "http:/schema.cfring. xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalocation = "http: htaMa http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http:/www.spramework.org/schema/beans http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/www.springframework.org/schema/schema/www.springframework.orga/schema/schema 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.xsdhtp://www.springframework.org/schema/cache id = "itemsservice"> </tac> </tobel>
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/orga/aPema/http://www.spramework.org/orga/aPema/sphema/www.spramework.org/orga/aPema/aPema/http" xmlns: cache = "http://www.springframework.org/schema/cache" xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http:/schema/context" xmlns: mvc = "http:/schema.cfring. xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalocation = "http: htaMa http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http:/www.spramework.org/schema/beans http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/www.spramework.org/schema/schema/www.spramework.org/schema/schema/www.spramework.org/schema/schema/www.spramework.org/schema/schema/www.spramework.org/schema/schema/sprammor 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.xsdhtp://www.springframework.org/schema/cache http:/www.spramework.org/schema/cache http: Mapper-> <!-mapper org.springframework.web.servlet.mvc.annotation.defaultAnnotationHandlermapping springmvc3.1-> <!-mapper org.springframework.web.servlet.mvc.annotation.defaultannotationShiMapping springmc.mvc.annotation.defaultAnnotationMappappappappappappappappapping org.springframework.web.servlet.mvc.method.annotation.requestmappingHandlermapping springmvc3.1 setelah-> <!-adaptor org.springframework.web.servlet.mvc.annotation.annotationMethodlerlerArdapter Sebelum springmvc3.1 --notation.annotationMethodllerArdapter Sebelum springmvc3.1-aDannotation org.springframework.web.servlet.mvc.method.annotation.requestmappingHandlerapter Setelah springmvc3.1-> <!-Mengkonfigurasi mapper dan adaptor <bean/> <bean/>-> <!-Nyalakan anotasi mapper dan adapter. Metode ini memuat banyak metode pengikatan parameter secara default, seperti parser konversi JSON-> <mvc: anotasi-digerakkan/> <!-Mengkonfigurasi pawang <bean/>-> <!-Konfigurasi anotasi didasarkan pada metode pemindaian-> <konteks: Komponen-scan base-paket = "com.jalja.sprolmc. Parser parameter khusus-> <mvc: layanan konversi yang digerakkan oleh anotasi = "conversionservice"/> <bean id = "conversionservice"> <name properti = "converters"> <cist> <!-Tipe Type Conversion-> <bean> </tanean> </list> </properti> </bean> <! Mengunggah file-> <bean id = "multipartresolver"> <!-ukuran file 5m-> <name properti = "maxuploadsize" value = "5242880"/> </ bean> <!-masalah akses sumber daya statis/JLOCET/JAGA/JAUS//JAGA/PENTING/JAGA/JAUS/JAUS/JAGA/JAGA/JAGA/JAGA/JAGA/JAGA/JAGA/JAGA/JAGA/JAGA/JAGE/JS/JS/JS/JS/JS/JS/JS/JS/JS/JS/JS/JS/JS/J. Konfigurasi Interceptor SpringMVC-> <mvc: Interceptors> <mvc: interceptor> <mvc: mapping path = "/**"/> <bean/> </mvc: interceptor> </mvc: pencegat> <!-lihat peta jsp parsing menggunakan jstl-> </mvc: Default> <! value = "org.springframework.web.servlet.view.jstlview"/> <name properti = "prefix" value = "/web-inf/jsp/"/> <name properti = "suffix" value = ".
F, config/jdbc.properties
jdbc_driverclassname = com.mysql.jdbc.driverjdbc_url = jdbc: mysql: // localhost: 3306/mybatis? UseUnicode = true & characterencoding = UTF-8JDBC_USERNAME = rootjdbc_password = 11111111111111111111111111111111111111
G, config/log4j.properties
#Dalam lingkungan pengembangan, level log harus diatur ke debug, lingkungan pembuatan harus diatur ke info atau errorLog4j.rootlogger = debug, stdoutlog4j.logger.org.apache.ibatis = debuglog4j.applog.stdout = org.apache.log4j.consoleAppenderlog4j.applay.stdout.layout = org.apache.log4j.patternlayoutlog4j.applay.applay.stdoUtdoCatser.conOout.conOblOut.cONObLOTLODY %M N
h, com/jalja/springmvc_mybatis/controller/itemscontroller.java
Paket com.jalja.springmvc_mybatis.controller; import java.io.file; impor java.util.list; impor java.util.uuid; impor org.springframework.beans.factory.annotation.Autowired; impor org.spramework.beans.factory.annotation.Autowired; impor org.spramework.beans.factory.annotation.Autowired; impor org.spramework.beans.factory.annotation.Autowired; impor org.spramework.beans.factory org.springframework.ui.model; impor org.springframework.web.bind.annotation.pathvariable; impor org.springframework.web.bind.annotation.requestbody; impor org.spramework.web.bind.annotation.requestbody; Impor; org.springframework.web.bind.annotation.requestmethod; impor org.springframework.web.bind.annotation.requestparam; impor org.springframework.web.bind.annotation.responseBody; impor org.springframework.wub.win com.jalja.springmvc_mybatis.exception.customException; import com.jalja.springmvc_mybatis.model.custom.itemscustom; com.jalja.springmvc_mybatis.servicessserviceSsService; SpringMVC menyediakan banyak konverter parameter*/@controller@requestMapping ("/item") // Pemetaan permintaan sempit kelas publik itemsController {@Autowired itemsService itemsService; @RequestMapping (value = "/findItemslist") Public String FindItemSlist (model model) Lemparan Exception {itemscustom "Daftar <item itemslist = itemsservice.findItemslist (null); System.out.println (itemslist); model.addattribute ("itemslist", itemslist); return "itemslist";}@requestMapping (value = "/editems", metode = {requestMethod.post, requestMethod.param.param) Parameter dengan Parameter Formal Diperlukan: Tentukan bahwa nilai atribut harus diteruskan dalam defaultValue: Tetapkan nilai default editor string publik (model model, @RequestParam (value = "id", wajib = true, defaultValue = "0") Integer itemSid) melempar pengecualian {itemscustom itemcustom = itemsservice.finditemsbyId (itemsid); if (itemscustom = null) {lempar customexception baru ("Produk tidak ada");} model.addattribute ("itemscustom", itemscustom); return "editItems";}@requestMappappap (value = "/edit edItems (value ="/public. itemsCustom,MultipartFile itemsPic) throws Exception{String uploadFileName=itemsPic.getOriginalFilename();//Get the uploaded file name if(itemsPic!=null && uploadFileName!=null && !uploadFileName.equals("")){String imagesPath="E://develop//upload//images//";String newFileName = uuid.randomuuid ()+unggahfileName.substring (unggahfileName.lastIndexof ("."), unggahfileName.length ()); file newfile = file baru (gambar+newFileName); itemspic.transferto (newfile); itemcustom.setpic (newFileName);} itemsservice.updateItemsById (id, itemscustom); return "Redirect: findItemslist.do"; //Redirect}//Use of JSON @ResponseBody: To object to json output @RequestBody: To request parameters to java object @RequestMapping(value="/jsonRequest")public @ResponseBody ItemsCustom jsonRequest(@RequestBody ItemsCustom itemsCustom) throws Exception{return itemsCustom;}//RestFul Style Pemrograman/RestfulRequest/{id}: Ini berarti lulus parameter pada posisi ini ke nama yang ditentukan oleh @pathvariable @RequestMapping (value = "/RestfulRequest/{id}") public @ResponseBody itemscustom restfUndRequest (@pathvariable ("id id) InteGerBody itemscustom RestfulRequest (@pathvariable (" ID ") IntoGerBody IntoGerBody itemscustom = itemsservice.finditemsbyId (id); return itemscustom;}}Di atas adalah kode contoh mybatis terintegrasi springmvc yang diperkenalkan kepada Anda oleh editor. Saya harap ini akan membantu Anda. Jika Anda ingin mengetahui informasi lebih lanjut, harap perhatikan situs web Wulin.com!