Simple configuration and application of Mybatis-plus and mybatis-plus

Source: Internet
Author: User

Simple configuration and application of Mybatis-plus and mybatis-plus

Mybatis-plus is an enhanced version of mybatis, which is written by the Chinese gods and can automatically generate code.
The configuration process is simple. First introduce two maven Dependencies

    <dependency>            <groupId>com.baomidou</groupId>            <artifactId>mybatis-plus</artifactId>            <version>2.0.6</version>        </dependency>        <dependency>            <groupId>org.apache.velocity</groupId>            <artifactId>velocity</artifactId>            <version>1.7</version>        </dependency>

One is mybatis-plus, and the other is the template engine velocity on which the Code depends.
Then replace sqlSeassionFactoryBean of mybatis with the plus enhanced version. The plug-in can be configured selectively.

<Bean id = "sqlSessionFactory" class = "com. baomidou. mybatisplus. spring. mybatisSqlSessionFactoryBean "> <property name =" dataSource "ref =" dataSource "/> <property value =" classpath:/mybatis-config.xml "name =" configLocation "/> <! -- Automatically scans the mapping. xml file --> <property name = "mapperLocations" value = "classpath: mapper/*. xml"> </property> <! -- MP global configuration injection --> <property name = "globalConfig" ref = "globalConfig"/> <! -- Plug-in configuration --> <property name = "plugins"> <array> <bean class = "com. baomidou. mybatisplus. plugins. optimisticLockerInterceptor "/> </array> </property> </bean>

Mybatis-plus global configuration, which mainly configures the id generation policy and depends on the database type,

<Bean id = "globalConfig" class = "com. baomidou. mybatisplus. entity. GlobalConfiguration"> <! -- Primary key policy configuration --> <! -- Optional parameter AUTO-> '0' ("Database id auto-increment") INPUT-> '1' (user input id ") ID_WORKER-> '2' ("Globally Unique ID") UUID-> '3' ("Globally Unique ID ") --> <property name = "idType" value = "2"/> <! -- Database Type Configuration --> <property name = "dbType" value = "mysql"/> <! -- Set true for the underline name in the global table --> <property name = "dbColumnUnderline" value = "true"/> </bean>

Generate code

Public class MpGenerator {/*** <p> * MySQL generation demonstration * </p> */public static void main (String [] args) {AutoGenerator mpg = new AutoGenerator (); // global configuration \ Begin \ src \ main \ java GlobalConfig gc = new GlobalConfig (); gc. setOutputDir ("G: \ workspace"); gc. setFileOverride (true); gc. setActiveRecord (true); gc. setEnableCache (false); // XML second-level cache gc. setBaseResultMap (true); // XML ResultMap gc. setBaseColumnList (tr Ue); // XML columList gc. setOpen (false); gc. setAuthor ("XuWei"); // custom file name. Note that % s will automatically fill the table object attributes! Gc. setMapperName ("% sDao"); gc. setXmlName ("% sMapper"); gc. setServiceName ("% sService"); gc. setServiceImplName ("% sServiceImpl"); gc. setControllerName ("% sController"); mpg. setGlobalConfig (gc); // configure the data source performanceconfig dsc = new performanceconfig (); dsc. setDbType (DbType. MYSQL); dsc. setDriverName ("com. mysql. jdbc. driver "); dsc. setUrl ("jdbc: mysql: // localhost: 3306/begin? UseUnicode = true & amp; characterEncoding = UTF-8 & amp; generateSimpleParameterMetadata = true "); dsc. setUsername ("root"); dsc. setPassword ("123"); mpg. setDataSource (dsc); // strategy Configuration StrategyConfig strategy = new StrategyConfig (); // strategy. setCapitalMode (true); // name the global capital statement in ORACLE. Pay attention to strategy. setTablePrefix (new String [] {"t _", "tsys _"}); // you can change it to your table prefix strategy. setNaming (NamingStrategy. underline_to_camel); // table name Generate strategy. setInclude (new String [] {"dept"}); // the table to be generated // strategy. setExclude (new String [] {"test"}); // exclude the generated table mpg. setStrategy (strategy); // The default values are service, serviceImpl, and controller. Disable them TemplateConfig tc = new TemplateConfig (); tc. setController (null); mpg. setTemplate (tc); // generate the file path // PackageConfig pc = new PackageConfig (); // pc. setParent ("com. xu "); // pc. setEntity ("entity. plus "); // pc. setMapper ("dao. plus "); // pc. setXml ("mapper. plus "); // pc. setService ("service. plus "); // pc. setServiceImpl ("service. plus. impl "); // mpg. setPackageInfo (pc); // run the command to generate mpg.exe cute ();}

The code is generated in the directory of G: \ workspace.
Compared with mybayis generator, the Code ing file xml generated by plus is cleaner than the dao layer. Common CRUD is implemented by BaseMapper inherited by dao class.
However, the disadvantage is also obvious. The condition constructor cannot directly map the field names in the table to pojo like generator. Therefore, you need to write the field names corresponding to the query conditions by yourself.
If you want to splice such a query condition (user_name =? And password =? ) Or (id =? And state =? )
Mybatis-plus condition Construction

EntityWrapper <User> ew = new EntityWrapper <> (); ew. eq ("user_name", "Ask the day "). eq ("password", "sde"); ew. orNew ("id", 3 ). eq ("state", 2 );

Mybatis generator condition Construction

UserExample userExample = new UserExample (); userExample. createCriteria (). andusernametransferto (" "). andPasswordEqualTo ("sde"); userExample. or (). andIdEqualTo (3 ). andStateEqualTo (2); userExample. isDistinct ();
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.