Common label configurations for common tags and mapper files in the MyBatis core configuration file

Source: Internet
Author: User
Tags aliases reflection sql injection wrapper
MyBatis Core configuration file (Sqlmapconfig.xml)

MyBatis Global configuration file Sqlmapconfig.xml, the configuration is as follows:

Properties (property)
settings (Global configuration parameter)
typealiases (type alias)
Typehandlers (type processor)
Objectfactory (object Factory)
Plugins (plug-in)
environments (Environment collection Property object)
Environment (Environment sub-Property object)
TransactionManager (transaction management)
DataSource (data source)
Mappers (mapper)
Properties Property

Requirements:

To configure the database connection parameters separately in Db.properties, you only need to load the Db.properties property values in Sqlmapconfig.xml.
You do not need to hard-code database connection parameters in Sqlmapconfig.xml.

The database connection parameters are only configured in Db.properties, because it is convenient to manage parameters uniformly, and other XML can refer to the db.properties in a clustered environment.

Sqlmapconfig.xml can refer to the configuration information in the Java properties file as follows:

Define the Db.properties file under src:

Jdbc.driver=com.mysql.jdbc.driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
Jdbc.password=mysql

Sqlmapconfig.xml references are as follows:

    <properties resource= "db.properties" ></properties>
    <environments default= "Development" >
        <environment id= "Development" >
        <!--using JDBC Transaction management, transaction control by Mybatis-->
            <transactionmanager Type= "JDBC"/>
        <!--database connection pool, managed by MyBatis and
            <datasource type= "Pooled" >
                <property name= " Driver "value=" ${jdbc.driver} "/>
                <property name=" url "value=" ${jdbc.url} "/>
                <property name=" Username "value=" ${jdbc.username} "/>
                <property name=" password "value=" ${jdbc.password} "/>
            < /datasource>
        </environment>
    </environments>

Note: MyBatis will load properties in the following order: attributes defined in the properties element are first read. It then reads the properties of the resource or URL loaded in the property element, overwriting properties that have been read with the same name.

Note: If the attribute defined in the Properties tab is referenced by ${}, it does not work for #{}. Then it does not read the parameter values inside the ParameterType. For example, the properties define the id attribute, the value is 40, reference the value in the mapping file, ${id} Then when I pass the value from ParameterType, no matter whether I pass the basic type or the reference type, the ${id} value will not be overwritten. will always read 40.

Even if I pass the parameter Java.lang.Interger or pass the custom wrapper class Cn.domarvel.User The ID value will not work. Eventually, it was deleted.

Therefore, if you use ${} to read the value, note that the property does not read the error. With #{}, these problems do not occur. #{} always reads the value inside the parametertype. I am using the MyBatis3.4.2 version.

To prevent ${}, it is common to use the Jdbc.username jdbc as the key prefix. Do not make mistakes if you know what you mean.

Recommendation:

Do not add any attribute values in the properties element, only the attribute values are defined in the property file.
It is necessary to define attribute names in the properties file, such as: XXXXX.XXXXX.XXXX settings (configuration)

MyBatis Global configuration parameters, global parameters will affect the running behavior of MyBatis.

Download address typealiases (type alias)

In Mapper.xml, defining a lot of statement,statement requires parametertype specifying the type of input parameter, the type of mapping that needs to be resulttype to specify the output result.

If you enter a type full path when specifying a type, it is inconvenient to develop, you can define some aliases for the type specified by ParameterType or Resulttype, and the alias definition in mapper.xml to facilitate development.

mybatis Support aliases:

aliases Types of Mappings
_byte Byte
_long Long
_short Short
_int Int
_integer Int
_double Double
_float Float
_boolean Boolean
String String
Byte Byte
Long Long
Short Short
Int Integer
Integer Integer
Double Double
Float Float
Boolean Boolean
Date Date
Decimal BigDecimal
BigDecimal BigDecimal

Custom Aliases:

Configured in Sqlmapconfig.xml (configuration in the MyBatis core configuration file):

    <typeAliases>
        <!--defines an alias for a single class, where the alias is User, when used in ParameterType and Resulttype, is not case-sensitive, user,user,user, User can-
        <typealias type= "Cn.domarvel.entity.User" alias= "user"/>
        <!--batch definition aliases (common), Here alias for the class name User, in ParameterType and Resulttype, when used, not case-sensitive, user,user,user,user can,
        Note:
            This does not support wildcard characters, such as: "*", "_", "?"
         --
        <package name= "cn.domarvel.entity"/>
    </typeAliases>
typehandlers (type processor)

The conversion of JDBC type and Java type is done through typehandlers in MyBatis.

Typically, MyBatis provides a type processor that meets daily needs and does not require customization.

MyBatis supports type processors:

Type Processor Java Type JDBC Type
Booleantypehandler Boolean,boolean Any of the compatible Boolean values
Bytetypehandler Byte,byte Any compatible number or byte type
Shorttypehandler Short,short Any compatible number or short integer
Integertypehandler Integer,int Any compatible number and integral type
Longtypehandler Long,long Any compatible number or long integer
Floattypehandler Float,float Any compatible digital or single-precision floating-point type
Doubletypehandler Double,double Any compatible digital or double-precision floating-point type
Bigdecimaltypehandler BigDecimal Any compatible number or decimal decimal type
Stringtypehandler String char and varchar types
Clobtypehandler String CLOB and LongVarChar types
Nstringtypehandler String nvarchar and nchar types
Nclobtypehandler String NCLOB type
Bytearraytypehandler Byte[] Any compatible byte stream type
Blobtypehandler Byte[] Blob and LongVarBinary types
Datetypehandler Date (Java.util) Timestamp type
Dateonlytypehandler Date (Java.util) Date type
Timeonlytypehandler Date (Java.util) Time Type
Sqltimestamptypehandler Timestamp (java.sql) Timestamp type
Sqldatetypehandler Date (java.sql) Date type
Sqltimetypehandler Time (java.sql) Time Type
Objecttypehandler Any Other or unspecified type
Enumtypehandler Enumeration type varchar-any compatible string type as a code store (not an index).
mappers tags (map configuration)

1. Loading a single mapping file via resource

Use resources relative to the classpath:

    <!--load a mapping file
    --<mappers>
        <!--load a mapping file under a single classpath--
        <mapper resource= "cn/domarvel/ Entity/user.xml "></mapper>
        <mapper resource=" Cn/domarvel/dao/usermapper.xml "></mapper>
    </mappers>

2.<mapper url= ""/>

Using fully qualified paths

<mapper url= "File:///d:\workspace_spingmvc\mybatis_01\config\sqlmap\user.xml"/>

3.<mapper class= ""/>

Using the Mapper interface class path

    <!--load a mapping file--
    <mappers>
        <!--load a single mapping file using Classpath--
        <mapper url= " Cn.domarvel.dao.UserMapper "/>
    </mappers>

Note: This method requires the Mapper interface name and the mapper mapping file name to be the same and to be placed in the same directory. And there is a premise that the Mapper proxy method is used

4.<package name= ""/>

Automatically bulk load all mapper interface profiles under the specified package

    <!--load the mapping file
        --<mappers> <!--automatically bulk load all mapper interface profiles under the specified package--
        <package name= " Cn.domarvel.dao "/>
    </mappers>

Note: This method requires the Mapper interface name and the mapper mapping file name to be the same and to be placed in the same directory. And there is a premise: using the Mapper proxy method mapper.xml file Common label configuration parametertype (input type) #{} and ${}

#{} implements a parameter value set to a preprocessing statement in Preparestatement, and the SQL statement #{} represents a placeholder.
<!--query user information by ID--
    <select id= "Finduserbyid" parametertype= "int" resulttype= "user" >
        SELECT * From user where id = #{id}
    </select>
Using the placeholder #{} can effectively prevent SQL injection, and when used without caring about the type of parameter values, MyBatis will automatically convert Java type and JDBC type. #{} can receive either a simple type value or a Pojo property value, and if ParameterType transmits a single simple type value, #{} parentheses can be either value or another name.
Unlike ${} and #{}, the ParameterType incoming content can be stitched into SQL without JDBC type conversion through ${}, and ${} can receive either a simple type value or a Pojo property value, if ParameterType transmits a single simple type value, ${} Only value can be in parentheses. Using ${} does not prevent SQL injection, but sometimes it is very convenient to use ${}, as in the following example:
<!--fuzzy query user information by name--
    <select id= "Selectuserbyname" parametertype= "string" resulttype= "user" >
       SELECT * from user where username like '%${value}% '
    </select>
If this example uses #{} then the passed in string must have the% number, and the% is artificial stitching in the parameters, it is obviously a bit cumbersome, if the use of ${} in SQL splicing as% in the way of calling the mapper interface to pass parameters is much easier.
If you use a placeholder symbol, you must add%
list<user> list = usermapper.selectuserbyname ("% Administrator%") in the argument.
If you use the ${} primitive symbol, you do not need to add%
list<user>list = usermapper.selectuserbyname ("Administrator") to the parameter;
For example, order by ordering, if you pass the column name through the parameter to SQL, according to the column name to be sorted, it should be written as:
ORDER by ${columnname}
if you use #{} will not be able to implement this feature.

In fact, parametertype attributes can not write, do not write or error. However, when you do not write, just know how to take it OK, but others look at your code does not necessarily know AH. Right.. So, we still have to write parametertype this property. Passing Pojo Objects

MyBatis uses the OGNL expression to parse the value of an object field, as in the following example:

<!-Pass Pojo Object Comprehensive query user information--
    <select id= "Finduserbyuser" parametertype= "user" resulttype= "user" >
       SELECT * from user where Id=#{id} and username like '%${username}% '
    </select>

Test:

public void Testfinduserbyuser () throws exception{
        //Get session
        sqlsession session = Sqlsessionfactory.opensession ();
        Limited Mapper Interface instance
        usermapper usermapper = Session.getmapper (usermapper.class);
        Constructs the query condition user Object
        User user = new user ();
        User.setid (1);
        User.setusername ("Administrator");
        Pass the User object query list
        list<user>list = usermapper.finduserbyuser (user);
        Close Session
        Session.close ();
    }

Exception test:

SQL field name input error after testing, username input dusername test results error:

Org.apache.ibatis.exceptions.PersistenceException: 
# # # Error querying database.  Cause:org.apache.ibatis.reflection.ReflectionException:There is no getter for property named ' Dusername ' in ' class cn.it Cast.mybatis.po.User '
# # Cause:org.apache.ibatis.reflection.ReflectionException:There is the no getter for property Named ' Dusername ' in ' Class Cn.itcast.mybatis.po.User '
passing Pojo wrapper objectsVo The view layer of things that can be passed from the view layer to the SERIVCE layer to the persistence layer. PO Persistence layer class, usually tied to database tables Vo and po all belong to the Pojo custom class entity represents the persistence layer of things and po almost

In the development of the query conditions through Pojo, query conditions are comprehensive query conditions, not only including the user query conditions also include other query conditions (such as the user to purchase product information also as a query condition), you can use the wrapper object to pass input parameters. Defining wrapper Objects

Defines the wrapper object to wrap the query criteria (POJO) in a class combination.

public class Queryvo {

    private user user;

    Custom user extension class
    private usercustom usercustom;

    At the same time each variable provides getter and setter methods
mapper.xml Mapping File

Description: MyBatis The bottom layer gets the property value from the Pojo by OGNL: #{user.username},user is the property of the wrapped object that is passed in. Queryvo is the alias, which is the wrapper object type defined above. Pass HashMap

The SQL mapping file is defined as follows:

<!--transfer HashMap Comprehensive query user information--
    <select id= "Finduserbyhashmap" parametertype= "HashMap" resulttype= "user" >
       SELECT * from user where Id=#{id} and username like '%${username}% '
    </select>

<!-- Where ID and username are hashmap key---

Test:

public void Testfinduserbyhashmap () throws exception{
        //Get session
        sqlsession session = Sqlsessionfactory.opensession ();
        Limited Mapper Interface instance
        usermapper usermapper = Session.getmapper (usermapper.class);
        Constructs the query condition HashMap object
        hashmap<string, object> map = new hashmap<string, object> ();
        Map.put ("id", 1);
        Map.put ("username", "Administrator");

        Pass HashMap object query user list
        list<user>list = Usermapper.finduserbyhashmap (map);
        Close Session
        Session.close ();
    }

Exception test: The key in the passed map is inconsistent with the key resolved in SQL. The test results are not error-free, only the value obtained by key is empty.

Application Scenarios:

When multiple parameters in SQL do not have any relationships, the Map collection type is used.
For example, select SUM (Score) as Sumscore, AVG (score) as Avgscore from user resulttype (output type) output Simple Type

Mapper.xml file

<!--get the total number of user lists-
    <select id= "Findusercount" parametertype= "user" resulttype= "int" >
       select Count (1) from user
    </select>

Mapper interface

public int findusercount (user user) throws Exception;

Call:

public void Testfindusercount () throws exception{
        //Get session
        sqlsession session = Sqlsessionfactory.opensession ();
        Get Mapper Interface instance
        usermapper usermapper = Session.getmapper (usermapper.class);

        User user = new user ();
        User.setusername ("Administrator");

        int count = usermapper.findusercount (user);

        Close Session
        Session.close ();
    }

Summary: The output simple type must be queried for a result set with a record that eventually converts the value of the first field to the output type. If SQL returns more than one piece of data, it returns only the first data, provided that Resulttype is a base type. (String,integer, which are not encapsulated by multiple attributes, are basic types.) For example, VO can encapsulate multiple attributes, encapsulate String,integer, etc., then it is a complex type. Use the SelectOne of the session to query a single record. Output Pojo Object

Refer to the definition of Finduserbyid:
Mapper.xml

    <!--query user information by ID--
    <select id= "Finduserbyid" parametertype= "int" resulttype= "user" >
        SELECT * From user where id = #{id}
    </select>

Mapper Interface:

Public User Finduserbyid (int id) throws Exception;

Test:

public void Testfinduserbyid () throws Exception {
        //Get session
        sqlsession session = Sqlsessionfactory.opensession ();
        Limited Mapper Interface instance
        usermapper usermapper = Session.getmapper (usermapper.class);
        Call Statement
        User user = Usermapper.finduserbyid (1) via the Mapper interface;
        SYSTEM.OUT.PRINTLN (user);
        Close Session
        Session.close ();
    }

Use session call SelectOne to query a single record. Output Pojo list

Refer to the definition of selectuserbyname:
Mapper.xml

<!--fuzzy query user information by name--
    <select id= "Finduserbyusername" parametertype= "string" resulttype= "User" >
       SELECT * from user where username like '%${value}% '
    </select>

Mapper Interface:

Public list<user> Finduserbyusername (String username) throws Exception;
Test: Public
void Testfinduserbyusername () throws exception{
        //Get session
        sqlsession session = Sqlsessionfactory.opensession ();
        Limited Mapper Interface instance
        usermapper usermapper = Session.getmapper (usermapper.class);
        If you use a placeholder symbol, you must add%
        //list<user> list = usermapper.selectuserbyname ("% Administrator%") in the argument.
        If you use the ${} primitive symbol, you do not need to add%
        list<user> list = usermapper.finduserbyusername ("Administrator") for the parameter;
        Close Session
        Session.close ();
    }

Use the SelectList method of the session to get the Pojo list. Resulttype Summary:

The output Pojo object and the output Pojo list are the same as those defined in SQL Resulttype.
Returns a single Pojo object to ensure that the result set of the SQL query is one, internally using the Session.selectone method call, the Mapper interface uses the Pojo object as the method return value.

The return Pojo list indicates that the result set of the query might be multiple, internally using the Session.selectlist method, and the Mapper interface uses the list object as the method return value. Output HashMap

The output Pojo object can use the HashMap output type instead, and the output field name as the key,value of the map is the field value. resultmap Resulttype can specify POJO to map the query results to Pojo, but the property name that needs to be pojo and the column name of the SQL query can be mapped successfully. If the SQL query field names and Pojo property names do not match, you can resultmap the field name and the property name a corresponding relationship, Resultmap essentially also need to map the query results to the Pojo object, that is, the resultmap tag inside the type attribute defined. The MyBatis framework is SQL-oriented, so the object is not related to SQL. MyBatis you convert the query results to objects of the specified type, you need to follow the rules of the transformation, Resulttype match the query result field name to the property name of the specified type, and if the match succeeds, make a reflection call and do nothing if the match is unsuccessful. In the case of the limit, a property does not match successfully. Then the object is not created and gets null. Instead resultmap can solve this problem. Resultmap can be used to map query results to complex types of pojo, such as including Pojo and list in query result mapping objects, implementing one-to-one queries and one-to-many queries. The query can be classified into the multi-object wrapper class of Vo. Like what:

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.