Spring Boot Tutorial V: Integrated mybaits

Source: Internet
Author: User

The

MyBatis framework has become a widely used database development tool, so here we do not talk about other database connection operations, go straight to the topic, integration mybaits:
First Modify the Pom file, introduce the relevant package:

    <dependencies> <!--exclude the default log frame--<dependency> <groupid>org.springfra Mework.boot</groupid> <artifactId>spring-boot-starter-web</artifactId> &LT;EXCLU
                    Sions> <exclusion> <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> &LT;GROUPID&GT;ORG.SPRINGF Ramework.boot</groupid> <artifactId>spring-boot-starter-test</artifactId> &LT;SC Ope>test</scope> </dependency> <!--log4j--> <dependency> & Lt;groupid>org.springframework.boot</groupid> &LT;ARTIFACTID&GT;SPRING-BOOT-STARTER-LOG4J&LT;/ARTIFAC Tid> <Version>1.3.8.release</version> </dependency> <!--druid--> <dependency>
            <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency> <!--database driver-<dependency&gt
            ; <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> &lt
            ;version>5.1.25</version> </dependency> <!--mybaits--<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactid>mybatis-spring-boot-starte 

        R</artifactid> <version>${mybatis.spring.boot.version}</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId> Commons-coLlections</artifactid> </dependency> </dependencies> 

Add the Mybaits configuration to the configuration file:

# mybatis Configuration
mybatis.mapperlocations=classpath:mapper/*.xml
mybatis.configlocation=classpath:config/ Mybatis.xml

Create a new config file under the Resources folder, and in the other new Mybatis.xml profile:

<?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"
; <configuration> <settings> <!--map underline automatic capitalization--<setting name= "Mapunderscoretocam
        Elcase "value=" true "/> <!--print query statement--<setting name=" Logimpl "value=" stdout_logging "/> <!--The return field is empty, null also displays the field-<setting name= "Callsettersonnulls" value= "true"/> </setting s> <!--alias definition-<typeAliases> <!--bulk alias definition, specifying package name, MyBatis automatically scans the PO class in the package, automatically defines aliases, alias is class name (uppercase or lowercase) Yes, usually lowercase)-<!--<package name= "Com.hotpot. Pojo "/>-<!--<typealias type=" Com.hotpot.sys.pojo.SysUser "alias=" Sysuser "/>--&L t;! ---Batch alias definition specifies the package name, MyBatis automatically scans the PO class in the package, automatically defines the alias, which is the class name (either uppercase or lowercase)-<!--<pack Age name= "Com.demo.pojo"/&Gt;--> </typeAliases> <plugins> <!--print SQL interceptors--<plugin interceptor= "Co M.springboot.interceptor.mybatisinterceptor "></plugin> </plugins> </configuration>

Then create a new mapper package, and create a new Usermapper interface class below:

/**
 * @Package: Com.springboot.test.mapper
 * @ClassName: Usermapper
 * @Description: User mapper class
 * @ Author Shuyu.wang
 * @Date 2017-12-07 17:27
 **/
@Mapper Public
interface Usermapper {

    List<map <String,Object>> listUsers ();
}

Then create a new Mapper folder under the Resources folder, and create a new Usermapper.xml file below:

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace= "Com.springboot.test.mapper.UserMapper" >

    <select id= "listUsers" resulttype= " Java.util.Map ">
        select * from user
    </select>

</mapper>

Then add the interface to the Web class:

     @Autowired
     private Usermapper usermapper;

    @RequestMapping (value = "/db", method = requestmethod.get) public
    list<map<string,object>> db () {
        return  usermapper.listusers ();
    }

In addition, create a new interceptor package, add an interceptor to print the full statement of SQL, including parameters, MyBatis will print the relevant query statements, but for complex statement operations, the Interceptor class can help us to more clearly trace the error, the code is as follows:

Package com.springboot.interceptor;
Import Org.apache.commons.collections.CollectionUtils;
Import Org.apache.ibatis.executor.Executor;
Import ORG.APACHE.IBATIS.MAPPING.BOUNDSQL;
Import org.apache.ibatis.mapping.MappedStatement;
Import org.apache.ibatis.mapping.ParameterMapping;
Import org.apache.ibatis.plugin.*;
Import Org.apache.ibatis.reflection.MetaObject;
Import org.apache.ibatis.session.Configuration;
Import Org.apache.ibatis.session.ResultHandler;
Import Org.apache.ibatis.session.RowBounds;
Import Org.apache.ibatis.type.TypeHandlerRegistry;

Import Org.apache.log4j.Logger;
Import Java.text.DateFormat;
Import Java.util.Date;
Import java.util.List;
Import Java.util.Locale;
Import java.util.Properties;


Import Java.util.regex.Matcher;
 /** * @Title: Mybatisinterceptor.java * @Package com.ganinfo.utils * @Description: Block print full SQL statement * @author Shuyu.wang * @date Creation time:2017 September 4 * @version V1.0 */@Intercepts ({@Signature (type = Executor.class, method = "Update ", ARGS = {mappedstatement.class, object.class}), @Signature (type = Executor.class, method = "Query", args = {Mapped Statement.class, Object.class, Rowbounds.class, resulthandler.class}) public class Mybatisinterceptor

    Implements Interceptor {private Logger Logger = Logger.getlogger (Mybatisinterceptor.class);

    @SuppressWarnings ("unused") private properties properties; @Override public Object intercept (invocation invocation) throws Throwable {try {mappedstatement
            Mappedstatement = (mappedstatement) invocation.getargs () [0];
            Object parameter = null;
            if (Invocation.getargs (). length > 1) {parameter = Invocation.getargs () [1];
            } String Sqlid = Mappedstatement.getid ();
            Boundsql boundsql = mappedstatement.getboundsql (parameter);
            Configuration configuration = Mappedstatement.getconfiguration (); String sql = GetSQL (configuratIon, Boundsql, Sqlid, 0);
            Logger.info ("*************");
            Logger.info ("* * *" +sql);
        Logger.info ("*************");
            } catch (Exception e) {e.printstacktrace ();
        Logger.error (e);
    } return Invocation.proceed (); public static string GetSQL (configuration configuration, Boundsql Boundsql, String sqlid, long time) {Stri
        ng sql = showsql (configuration, boundsql);
        StringBuilder str = new StringBuilder (100);
        Str.append (Sqlid);
        Str.append (":");
        Str.append (SQL);
    return str.tostring ();
        } private static String Getparametervalue (Object obj) {string value = null;
        if (obj instanceof String) {value = "'" + obj.tostring () + "'"; } else if (obj instanceof Date) {DateFormat formatter = dateformat.getdatetimeinstance (Dateformat.default, Da
            Teformat.default, Locale.china); Value = "'" + Formatter.format(New Date ()) + "'";
            } else {if (obj! = null) {value = Obj.tostring ();
            } else {value = "";
    }} return value; }/** * @param configuration * @param boundsql * @return */public static String Showsql (Conf
        Iguration configuration, Boundsql boundsql) {Object parameterobject = Boundsql.getparameterobject ();
        list<parametermapping> parametermappings = Boundsql.getparametermappings ();
        String sql = Boundsql.getsql (). ReplaceAll ("[\\s]+", "" "); if (Collectionutils.isnotempty (parametermappings) && parameterobject! = null) {typehandlerregistry ty
            Pehandlerregistry = Configuration.gettypehandlerregistry (); if (Typehandlerregistry.hastypehandler (Parameterobject.getclass ())) {sql = Sql.replacefirst ("\ \", Matche

            R.quotereplacement (Getparametervalue (Parameterobject)));
 } else {               MetaObject metaobject = Configuration.newmetaobject (Parameterobject); for (parametermapping parametermapping:parametermappings) {String propertyname = PARAMETERMAPPING.G
                    Etproperty ();
                        if (Metaobject.hasgetter (PropertyName)) {Object obj = Metaobject.getvalue (propertyname);
                    sql = Sql.replacefirst ("\ \", Matcher.quotereplacement (Getparametervalue (obj))); } else if (Boundsql.hasadditionalparameter (PropertyName)) {Object obj = Boundsql.getadditionalpar
                        Ameter (PropertyName);
                    sql = Sql.replacefirst ("\ \", Matcher.quotereplacement (Getparametervalue (obj)));
                    } else {sql = Sql.replacefirst ("\ \", "missing");
    }//Print out missing, remind the parameter missing and prevent dislocation}}} return SQL; } @Override public Object Plugin (object target) {return Plugin.wrap (target, this);
    } @Override public void SetProperties (Properties properties0) {this.properties = Properties0;
 }
}

Launch program, visit: http://127.0.0.1:8082/boot/db
Return:

[{"Password": "123123", "address": null, "Phone": "12312312312", "UserName": "Adolf", "UserId": 1, "account": "Ah"}]

The console prints as follows:

Then visit: http://127.0.0.1:8082/boot/druid2/index.html
Log in and click SQL Monitoring:

We can monitor the specific statements and related parameters of our operation.

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.