MyBatis Learning 16 Custom Type Processor Typehandlers Introduction __mybatis

Source: Internet
Author: User

This article blog address: http://blog.csdn.net/soonfly/article/details/65628372 (reprint please indicate the source)
When we write the configuration file of the Mapper mapper, we inadvertently have used the type conversion, but MyBatis help us to complete.

<update id= "Update" parametertype= "Twm.mybatisdemo.pojo.User" >
    update User set
    Username=#{username}, Password=#{password},address=#{address}  where id=#{id}
</update>

As in the example above, just pass in a user object to the Update method, mybatis the user object with reflection, and then set the parameters in the preprocessing statement (PreparedStatement) based on the fields in the object, and use Setxxx () based on the type of the field. method to set the corresponding value. XXX can be a Java type such as Integer,string,date.
Similarly, when you remove a value from a result set (ResultSet), the data is converted to a Java object using methods such as Rs.getint, rs.getstring, and Rs.gettimestamp.

So the question is, who is going to decide javatype and Jdbctype's transition relationship? This is the function of the type processor (types handlers).
For example java.lang.String turn into Jdbc.varchar,java.lang.integer into Jdbc.int. MyBatis uses a built-in type processor to convert all basic data types, basic types of wrapper types, byte[, Java.util.Date, Java.sql.Date, Java,sql. Time, Java.sql.Timestamp, Java enumeration type, and so on.

But what about custom types?
Suppose the above address is varchar (50) In the database field type, but the Address field in the Java Twm.mybatisdemo.pojo.User class is not a string type, but rather a custom address type:

public class Address {
    String province;
    String City;
    Public address () {} public address
    (String province, String city) {
        this.province = province;
        this.city = city;
    }
    Getter and setter ...
}

Encounter this kind of situation, MyBatis basic Meng Force ...
If you run it, you report an error:

Type handler is null on parameter mapping to property ' address '. It
was either to specified and/or could not is found for the Javatype/
Jdbctype combination specified.

The address field needs to be passed to #{address}, and the addressing field is of type mybatis does not know what to do with this type of object.
Therefore, you need to create a custom type processor (Typehandler).

1. Create type Processor:

Class Addresstypehandler extends basetypehandler<address>{
}

By automatically generating code from the IDE, you can see that the parent class Basetypehandler has four methods that we need to implement, including three get methods, and a set method.

2. Implement Get Method
All three get methods are used to convert the Address field in the recordset obtained by the database to the Java address type object.
So we first add a construction method to the address class that uses: to generate an instance object from a string.

Let's say that the string we store in db is a "," number that separates provincial and municipal relations with the public address
(string address) {  
    != null) {  
        string[] segments = Address.split (",");  
        if (Segments.length > 1) {  
            this.province = segments[0];
            this.city = segments[1];  
        } 
        else if (Segments.length > 0) {  
            this.city = segments[0];  
        }  
    }  
}

Then implement the three get methods in the Addresstypehandler class: (compulsive disorder, don't like to see Arg0,arg1.) So by the way also change it)

@Override Public Address
Getnullableresult (ResultSet rSet, String columnName)
        throws SQLException {
    Return to new Address (rset.getstring (columnName));
}

@Override Public Address
Getnullableresult (ResultSet rSet, int columnindex)
        throws SQLException {
    return New Address (rset.getstring (columnindex));
}

@Override Public Address
Getnullableresult (callablestatement cstatement, int columnindex)
        throws SQLException {return to
    new address (cstatement.getstring (columnindex));
}

3. Implement Set Method

A set method is a type that is used to convert a Java type into a database store.
Here we first implement the ToString () method of the Address class (if ToString has it in another case, use a different method name)

@Override public
String toString () {return
    this.province + "," + this.city;
}

Then implement the Setnonnullparameter in the Addresstypehandler class

@Override public
void Setnonnullparameter (preparedstatement pstatement, int index, address
        , Jdbctype Jdbctype) throws SQLException {
    pstatement.setstring (index, address.tostring ());

4. Register the class in the MyBatis configuration file

<!--register a custom type processor-->
<typeHandlers>
    <typehandler handler= " Twm.mybatisdemo.type.AddressTypeHandler "/>
</typeHandlers>

Here's a little episode, I was at the end of the configuration file inserted this paragraph, the result prompts an error:

The content of element type "configuration" must match
"(Properties?,settings?,typealiases?,typehandlers?,objectfactory?,objectwrapperfactory?,reflectorfactory?, Plugins?,environments?,databaseidprovider?,mappers?) ".

Originally in the configuration label, must follow the prompts in this order to write, or the error.
Therefore typehandlers must be placed in front of the environments, typealiases behind.
In retrospect, it is similar to the way serialization/deserialization is felt.

This article blog address: http://blog.csdn.net/soonfly/article/details/65628372 (reprint please indicate the source)

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.