Springboot | Nineth Chapter: Integration and use of Mybatis-plus

Source: Internet
Author: User
Tags int size unique id

Objective

This section begins 数据访问 with an introduction to the relevant knowledge points. For back-end developers, dealing with the database is done every day, so a ORM框架 good one is necessary. Currently, the majority of companies choose MyBatis Frameworks as the underlying database persistence framework.

Just a few more words.

Looking at the current Mybatis frame of the big line of its way, I can not help but remember that the university period, at that time is still hibernate the era, has now basically forgotten. At that time, Mybatis the predecessor of the iBatis book appeared in a chapter. At that time the university teacher means: At present, the domestic basic no use iBatis of the company, so this chapter skipped, slightly, too ... Now to this still fresh memory, look at now Mybatis big line of its way, can not help but regrettable ah.

    • Mybatis-plus
    • Springboot Integration
    • Simple example
    • About transactions
    • Entity Object fields are enumeration classes
    • Summarize
    • At last
    • Cliché
Mybatis-plus

Mybatis-plus (MP) is a Mybatis enhancement tool that only makes enhancements and does not change on the basis of Mybatis, and is born to simplify development and improve efficiency.

Official website: http://mp.baomidou.com

Simply put, Mybatis-Plus is Mybatis the Enhanced toolkit, which simplifies the CRUD operation, provides 代码生成器 , and 条件构造器 is powerful (this is one of my favorites), with built-in multiple utility plugins: Standard plugins, plugins 分页 性能分析 , plugins, 全局拦截 etc. Make the development process, the basic paradigm code is a sentence to solve, save a lot of repetitive operation (the meaning of the existence of the program ape, agreed to let us move bricks it!) )。

Springboot Integration

The Mybatis-plus version chosen here is: 2.1.9 ,
The Mybatisplus-spring-boot-starter version is: 1.0.5 .
The corresponding MyBatis version is:3.4.5

0. Here user is a table for example, the database is MySQL

DROP TABLE IF EXISTS `user`;CREATE TABLE `user` (  `id` bigint(20) DEFAULT NULL COMMENT ‘唯一标示‘,  `code` varchar(20) DEFAULT NULL COMMENT ‘编码‘,  `name` varchar(64) DEFAULT NULL COMMENT ‘名称‘,  `status` char(1) DEFAULT ‘1‘ COMMENT ‘状态 1启用 0 停用‘,  `gmt_create` datetime DEFAULT CURRENT_TIMESTAMP COMMENT ‘创建时间‘,  `gmt_modified` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ‘修改时间‘) ENGINE=InnoDB DEFAULT CHARSET=utf8;

1. Pom dependency:

  <!--mybatis plus -->    <dependency>        <groupId>com.baomidou</groupId>        <artifactId>mybatisplus-spring-boot-starter</artifactId>        <version>1.0.5</version>    </dependency>    <dependency>        <groupId>com.baomidou</groupId>        <artifactId>mybatis-plus</artifactId>        <version>2.1.9</version>    </dependency>

2. Configuration file (can also be directly used @bean or through the application configuration file, see the official website)
Spring-mybatis.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd > <!--Create a JDBC data source directly using Ali's Druid database connection pool--<bean id= "DataSource" class= "Com.alibaba.druid.pool.DruidDataS Ource "destroy-method=" Close "> <property name=" driverclassname "value=" ${mysql.driver} "/> <prope Rty name= "url" value= "${mysql.url}"/> <property name= "username" value= "${mysql.username}"/> <pro Perty name= "Password" value= "${mysql.password}"/> <!--Initialize connection size--<property name= "InitialSize" value= "0"/> <!--connection pool maximum use of connections-<property Name= "maxactive" value= "/> <!--connection Pool Max free--<property name=" Maxidle "value="/> " <!--connection Pool min Idle--<property name= "Minidle" value= "0"/> <!--get connection Max wait Time-<prope Rty name= "maxwait" value= "60000"/> <property name= "validationquery" value= "${validationquery}"/> &L T;property name= "Testonborrow" value= "false"/> <property name= "Testonreturn" value= "false"/> &LT;PR Operty name= "Testwhileidle" value= "true"/> <!--configuration interval to detect the idle connection that needs to be closed, in milliseconds--and <property NA Me= "Timebetweenevictionrunsmillis" value= "60000"/> <!--Configure the minimum lifetime of a connection in the pool, in milliseconds--and <property Nam E= "Minevictableidletimemillis" value= "25200000"/> <!--open removeabandoned function--<property name= "R Emoveabandoned "value=" true "/> <!--1800 seconds, i.e. 30 minutes--<property name=" Removeabandonedtimeout "va lue= "1800"/> <!        --Output error log when abanded connection is turned off--<property name= "logabandoned" value= "true"/> <!--monitoring database-- <property name= "Filters" value= "Mergestat"/> </bean> <!--(transaction management) transaction manager, use Jtatransacti Onmanager for Global TX--<bean id= "TransactionManager" class= "Org.springframework.jdbc.datasource.Dat Asourcetransactionmanager "> <property name=" dataSource "ref=" DataSource "/> </bean> <!--available Over annotation control transactions--<tx:annotation-driven transaction-manager= "TransactionManager"/> <!--mybatis--> <be An id= "sqlsessionfactory" class= "Com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean" > <property na Me= "DataSource" ref= "DataSource"/> <!--automatically scans mapper.xml files, supports wildcards--<property name= "Mapperlocatio NS "value=" Classpath:mapper/**/*.xml "/> <!--configuration files, such as parameter configuration (whether to start hump, etc.), plug-in configuration, etc.-<property name=" conf Iglocation "Value=" clAsspath:mybatis/mybatis-config.xml "/> <!--enable aliases so that you do not have to write the full path class name, you can check your data--<property name=" TypeA Liasespackage "value=" cn.lqdev.learning.springboot.chapter9.biz.entity "/> <!--MP global Configuration Injection---&LT;PR Operty name= "GlobalConfig" ref= "GlobalConfig"/> </bean> <bean id= "GlobalConfig" class= "Com.baomidou.myba Tisplus.entity.GlobalConfiguration "> <!--auto-> ' 0 ' (" Database ID self-increment ") QW input-> ' 1 ' (user input ID ") id_worker-> ' 2 ' (" Globally unique ID ") uuid-> ' 3 ' (" Globally unique ID ")--<property name=" Idty PE "value=" 3 "/> </bean> <bean class=" Org.mybatis.spring.mapper.MapperScannerConfigurer "> <!-- Automatically scan package path, interface is automatically registered as a bean class---<property name= "Basepackage" value= "Cn.lqdev.learning.springboot.chapter9.biz.dao "/> </bean></beans>

3. Write the startup class to automatically load the configuration XML file when the app starts

/** *  mybatisPlus 配置类,使其加载配置文件 * @author oKong * */@Configuration@ImportResource(locations = {"classpath:/mybatis/spring-mybatis.xml"})//@MapperScan("cn.lqdev.learning.springboot.chapter9.biz.dao")//@EnableTransactionManagementpublic class MybatisPlusConfig {}

At this point, the mybatis-plus configuration is complete, and next, 代码生成器 create the required dao , mapper generic CRUD service class at once.
4. Writing code generator classes
Because the generator relies on velocity the template engine, it needs to join the dependency:

    <dependency>        <groupId>org.apache.velocity</groupId>        <artifactId>velocity-engine-core</artifactId>        <version>2.0</version>        <scope>test</scope>    </dependency>

Mysqlgenerator, this class is longer, and the related configuration can be changed according to the actual information.

public class Mysqlgenerator {private static final String package_name = "Cn.lqdev.learning.springboot.chapter9";    private static final String module_name = "Biz";    private static final String Out_path = "D:\\develop\\code";    private static final String AUTHOR = "Okong";    private static final String DRIVER = "Com.mysql.jdbc.Driver"; private static final String URL = "Jdbc:mysql://127.0.0.1:3306/learning?useunicode=true&characterencoding=utf-8"    ;    Private static final String user_name = "root";    private static final String PASSWORD = "123456"; /** * <p> * MySQL Generate Demo * </p>/public static void main (string[] args) {//custom needs to be populated        The field list<tablefill> tablefilllist = new arraylist<tablefill> (); Code generator Autogenerator mpg = new Autogenerator (). Setglobalconfig (//Global configuration New Globalc Onfig (). Setoutputdir (Out_path)//Output directory. Setfileoverride (TRUE)//overwrite file                       . Setactiverecord (TRUE)//Turn on ActiveRecord mode. Setenablecache (FALSE)//XML level two slow Save. Setbaseresultmap (FALSE)//XML Resultmap. Setbasecolumnlist (TRUE)//XML CO                        Lumlist. Setauthor (AUTHOR)//custom file naming, note that%s will automatically populate the table entity properties! . Setxmlname ("%smapper"). Setmappername ("%sdao")//. Setservicename ("Mp%sservice")//. Setserviceimplname ( "%sservicediy")//. Setcontrollername ("%saction")). Setdatasource (//Data source configuration NE                            W datasourceconfig (). Setdbtype (DBTYPE.MYSQL)//database type. Settypeconvert (new Mysqltypeconvert () { Custom database table field type conversion "optional" @Override public DbColumn                                Type Processtypeconvert (String fieldtype) {System.out.println ("conversion type:" + FieldType);if (Fieldtype.tolowercase (). Contains ("tinyint")) {//return dbcolumntype.boolean;                            } return Super.processtypeconvert (FieldType); }}). Setdrivername (DRIVER). Setusername (user_name). SetPassword (PASSWORD). SetUrl (URL)                                ). Setstrategy (//policy configuration New Strategyconfig ()                                . Setcapitalmode (TRUE)//global capitalization naming. Setdbcolumnunderline (TRUE)//global underline naming . Settableprefix (New string[]{"Demo_"})//Here you can modify the prefix for your table. Setnam ING (Namingstrategy.underline_to_camel)//Table name generation Policy//. Setinclude (New string[] {"demo_org"})/ /need to generate tables//. Setexclude (New string[]{"Test"})//Exclude generated tables//From                Define entities, public fields                . Setsuperentitycolumns (New string[]{"test_id"}). Settablefilllist (Tablef illlist)//Custom Entity parent class//. Setsuperentityclass ("com.baomidou.de Mo.common.base.BsBaseEntity ")/////Custom Mapper parent class//. Setsup                                Ermapperclass ("Com.baomidou.demo.common.base.BsBaseMapper")/////Custom Service parent class                                . Setsuperserviceclass ("Com.baomidou.demo.common.base.BsBaseService") Custom Service Implementation Class parent class//. Setsuperserviceimplclass ("Com.baomidou.demo.common.base.BsBas Eserviceimpl ")//Custom Controller parent class//. SETSUPERCONTROLLERCL                                ("Com.baomidou.demo.TestController")//"Entity" generates field constants (False by default) public static Final String ID = "test_id"; . Setentitycolumnconstant (TRUE)//"entity" is the builder model (default false)//                                Public User setName (String name) {this.name = name; return this;} . Setentitybuildermodel (TRUE)//"entity" is the Lombok model (default false) <a href= "Https://projectlombok. org/">document</a> Setentitylombokmodel (True)//Boolean Type field is removed is                Prefix processing//. Setentitybooleancolumnremoveisprefix (True)//. Setrestcontrollerstyle (True)                        . Setcontrollermappinghyphenstyle (True)). Setpackageinfo (//package configuration                                New Packageconfig (). Setmodulename (module_name). SetParent (package_name)//Custom package path . Setcontroller ("Controller")//This is the controller package name, Default web. Setxml ("Mapper"). Setmapper ("DaO ")). Setcfg (//Inject custom configuration, you can use the value of the CFG.ABC setting in the VM new Injectio                                Nconfig () {@Override public void Initmap () {                                map<string, object> map = new hashmap<string, object> ();                                Map.put ("abc", This.getconfig (). Getglobalconfig (). Getauthor () + "-mp");                            This.setmap (map); }}.setfileoutconfiglist (Collections.<fileoutconfig>singleton                                    List (new Fileoutconfig ("/TEMPLATES/MAPPER.XML.VM") {//Custom output file directory                                        @Override public String outputFile (Tableinfo tableinfo) {                                    return Out_path + "/xml/" + tableinfo.getentityname () + "Mapper.xml";   }                             })). SetTemplate (//Turn off default XML generation, adjust build to root directory New Templateconfig (). Setxml (NULL)//Custom template configuration, template can refer to the source code/mybatis-plus/src/main/resources/template use Cop        Y//to your project Src/main/resources/template directory, the template name can also be customized with the following configuration://. Setcontroller ("...");        . Setentity ("...");        . Setmapper ("...");        . Setxml ("...");        . Setservice ("...");        . Setserviceimpl ("...");        );    Execute build mpg.execute (); }}

After the operation can, save a lot of things!

Simple example

Simple demo under the use of adding and removing changes and paging.

When using paging, you mybatis-config.xml need to include a paging plugin:PerformanceInterceptor

    <plugins>      <!-- 分页插件配置 -->      <plugin interceptor="com.baomidou.mybatisplus.plugins.PaginationInterceptor"></plugin>    </plugins>

Writing the control layer

/** * User Control layer Simple demo additions and deletions and pagination * @author okong * */@RestController @requestmapping ("/user") public class Usercontroller {@Autow        Ired Iuserservice UserService;    @PostMapping ("add")//normal business, there is a need for transaction control within the user class, the control layer is generally not business control. @Transactional (rollbackfor = exception.class) public map<string,string> addUser (@Valid @RequestBody userreq US        Erreq) {User user = new User ();        User.setcode (Userreq.getcode ());        User.setname (Userreq.getname ());        Because the primary key policy ID is set,//user.setid (0L) is automatically generated without assigning a value.        Userservice.insert (user);        map<string,string> result = new hashmap<string,string> ();        Result.put ("Respcode", "01");        Result.put ("Respmsg", "new success");        Transaction Test//SYSTEM.OUT.PRINTLN (1/0);    return result;                } @PostMapping ("Update") Public map<string,string> updateUser (@Valid @RequestBody userreq userreq) { if (userreq.getid () = = NULL | | "". Equals (Userreq.getid ())) {throW New commonexception ("0000", "Update ID cannot be empty");        User user = new user ();        User.setcode (Userreq.getcode ());        User.setname (Userreq.getname ());                User.setid (Long.parselong (Userreq.getid ()));        Userservice.updatebyid (user);        map<string,string> result = new hashmap<string,string> ();        Result.put ("Respcode", "01");        Result.put ("Respmsg", "update Success");    return result;        } @GetMapping ("/get/{id}") Public map<string,object> GetUser (@PathVariable ("id") String ID) {//query        User user = Userservice.selectbyid (ID);        if (user = = null) {throw new Commonexception ("0001", "User id:" + ID + ", not Found"); } Userresp resp = Userresp.builder (). ID (User.getid (). toString ()). Code (User.getcode (        ). Name (User.getname ()). Status (User.getstatus ()). build (); map<string,object> result = new Hashmap<string,oBject> ();        Result.put ("Respcode", "01");        Result.put ("Respmsg", "success");        Result.put ("Data", resp);    return result; } @GetMapping ("/page") public map<string,object> pageuser (int current, int size) {//pagination page& Lt        user> page = new Page<> (current, size);        map<string,object> result = new hashmap<string,object> ();        Result.put ("Respcode", "01");        Result.put ("Respmsg", "success");        Result.put ("Data", Userservice.selectpage (page));    return result; }        }

Once the app is launched, postman access the corresponding URL address in turn.
New

Database:

Pagination

Because the profiling plug-in is configured, the console outputs the SQL statements executed

The others are not mapped.

About transactions

Under normal circumstances, only need to join in the service layer @Transactional , the transaction related to this section is not elaborated, then the opportunity will be a special chapter to explain.

Example in order to facilitate, directly in the control layer into the @Transactional transaction test, the formal development process, it is strongly recommended that the service layer of business control, the control layer is generally a logical judgment!

Entity Object fields are enumeration classes

Perhaps in the actual development, you will encounter, for convenience, some types, state fields will be written into enumeration type, such as Enable State: DISABLE ("0"), enable ("1"). In this case, the typeHandlers custom type of processing can be configured, here is simple to EnumOrdinalTypeHandler(存储enum类里的序号值) make an example, of course, can also be customized according to the needs of the processor, such as writing a generic enumeration converter, and other relevant knowledge points, we can self-Google.

Statusenums

public enum StatusEnum {        DISABLE,    ENABLE;}

Modifying a user object to an enumeration type

    /**     * 状态1 启用 0 停用     */    private StatusEnum status;

Configuration file mybatis-config.xml Join processing class

    <typeHandlers>       <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler"         javaType="cn.lqdev.learning.springboot.chapter9.biz.entity.StatusEnum"/>    </typeHandlers>

The conversion will be done automatically after that. You can download the sample for practical operation.

Summarize

This chapter is mainly for Mybatis-plus the integration and simple use of the description, detailed usage, can be viewed on the official website, the official website has detailed use guide, here is not swim. At this point, for the general development needs are basically satisfied. The following chapters will focus on the use of other supporting tools, so please look forward to it!

At last

At present, many big guys on the internet have a springboot series of tutorials, if there is a similar, please forgive me. This article is the author in front of the computer word knocking, each step is practice. If there is something wrong in the text, also hope to put forward, thank you.

Cliché
    • Personal QQ:499452441
    • Public Number:lqdevOps

Personal blog: https://blog.lqdev.cn

Complete Example: chapter-9

Original address: http://blog.lqdev.cn/2018/07/21/springboot/chapter-nine/

Springboot | Nineth Chapter: Integration and use of Mybatis-plus

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.