Mybatis BASICS (3) ---- SqlMapConfig. xml global configuration file parsing, mybatis getting started tutorial

Source: Internet
Author: User

Mybatis BASICS (3) ---- SqlMapConfig. xml global configuration file parsing, mybatis getting started tutorial
I. Content and configuration SEQUENCE OF THE SqlMapConfig. xml configuration file are as follows:

  • Mappers)
  • Ii. properties

    Purpose: separately configure the data connection in the db. properties, only need to be in SqlMapConfig. load db in xml. properties attribute value in SqlMapConfig. in xml, you do not need to hard encode the database connection parameters. Database Connection parameters are only configured in db. properties to facilitate unified management of parameters. Other xml can reference this db. properties.

    Content of db. properties:

    jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatisjdbc.username=rootjdbc.password=root

    Load db. properties in SqlMapConfig. xml

    <! -- Load database file db. properties -->
    <Properties resource = "db. properties"> <! -- Properties can also be configured with some attribute names and attribute values. Here, the attribute values are preferentially loaded --> <! -- <Property name = "driver" value = ""/> --> </properties> <! -- After integration with spring, environments configuration will be abolished --> <environments default = "development"> <environment id = "development"> <! -- Use jdbc transaction management, and the transaction control is managed by mybatis --> <transactionManager type = "JDBC"/> <! -- Database connection pool, managed by mybatis --> <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>

    Properties features:

    Note:

    • Properties defined in the properties element are read first.
    • Then, read the properties loaded by resource or url in the properties element, which overwrites the read attributes of the same name.
    • Finally, read the properties passed by parameterType, which overwrites the read attributes of the same name.

    Suggestion:

    Do not add any attribute values to the properties element. Only the attribute values are defined in the properties file.

    Attribute names defined in the properties file must have some special characteristics, such as xxxx. xxxx (jdbc. driver)

    Iii. settings global parameter configuration

    You can adjust some running parameters when running the mybatis framework. For example, enable Level 2 Cache and enable delayed loading. Global parameters affect the running behavior of mybatis.

    Configuration attributes and descriptions of mybatis-settings

    Setting) Description) Valid Values (Verification value group) Default (Default)
    CacheEnabled Enable or disable cache configuration globally for any er under this configuration. True | false TRUE
    LazyLoadingEnabled Enable or disable delayed loading globally. When disabled, all associated hot loads. True | false TRUE
    AggressiveLazyLoading When it is enabled, objects with delayed loading attributes will be fully loaded and then call any lazy attributes. Otherwise, each attribute is loaded as needed. True | false TRUE
    MultipleResultSetsEnabled Allow or disallow multiple result sets to be returned from a separate statement (requiring a compatible driver. True | false TRUE
    UseColumnLabel Use column labels instead of column names. In this regard, different drivers have different behaviors. Refer to the driver document or test two methods to determine how your driver acts. True | false TRUE
    UseGeneratedKeys Allows JDBC to support generated keys. Compatible drivers are required. This setting forces the generated key to be used. If it is set to true, some drivers will not be compatible, but will still work. True | false FALSE
    AutoMappingBehavior Specifies how MyBatis automatically maps columns to fields/attributes. NONE automatic ing. PARTIAL only automatically maps results without nested result ing definitions. FULL will automatically map the results to any complex (including nesting or other ).

    NONE, PARTIAL, FULL

    PARTIAL
    DefaultExecutorType Configure the default executor. SIMPLE executors do have nothing special. REUSE the executor to REUSE prepared statements. BATCH executor reuse statement and BATCH update.

    SIMPLE, REUSE, BATCH

    SIMPLE
    SafeRowBoundsEnabled The nested statement RowBounds is allowed. True | false FALSE
    MapUnderscoreToCamelCase Enable Automatic ing from the classic database column name A_COLUMN to the classic Java attribute name aColumn of the camel identity. True | false FALSE
    Localcached MyBatis uses the local cache to prevent loop reference and accelerate repeated nested queries. All query caches executed during a SESSION by default. If localCacheScope = STATMENT is used for statement execution, the same SqlSession is not called between two different data sharing sessions.

    SESSION

    STATEMENT

    SESSION
    DbcTypeForNull If it is null, no specific JDBC Type parameter is specified. Some drivers need to specify the JDBC Type of the column, but OTHER drivers such as NULL, VARCHAR, or OTHER work with common values. JdbcType enumeration. Most common are: NULL, VARCHAR and OTHER OTHER
    LazyLoadTriggerMethods Specifies the method of the object that triggers the delayed loading. A method name list separated by commas Equals, clone, hashCode, toString
    DefaultScriptingLanguage The specified language is generated by dynamic SQL by default. A type alias or fully qualified class name.

    Org. apache. ibatis. scripting. xmltags

    . XMLDynamicLanguageDriver

    CallSettersOnNulls Specify that if the setter method or map put method is used, the retrieved value is null. It is useful when you rely on Map. keySet () or null for initialization. Note that primitives (such as integer and Boolean) are not set to null. True | false FALSE
    LogPrefix The specified prefix string. MyBatis will add the recorder name. Any String Not set
    LogImpl Specify the log Implementation of MyBatis. If this setting does not exist, the record will be automatically searched. SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING Not set
    ProxyFactory If you specify a proxy tool, MyBatis will use the object that creates the lazy loading capability. CGLIB | JAVASSIST CGLIB

    Example of settings in the official document

    <Setting name = "cacheEnabled" value = "true"/> <setting name = "lazyLoadingEnabled" value = "true"/> <setting name = "multipleResultSetsEnabled" value = "true" /> <setting name = "useColumnLabel" value = "true"/> <setting name = "useGeneratedKeys" value = "false"/> <setting name = "autoMappingBehavior" value =" PARTIAL "/> <setting name =" defaultExecutorType "value =" SIMPLE "/> <setting name =" defaultStatementTimeout "value =" 25 "/> <setting name =" safeRowBoundsEnabled "value = "false"/> <setting name = "mapUnderscoreToCamelCase" value = "false"/> <setting name = "localcached" value = "SESSION"/> <setting name = "jdbcTypeForNull "value =" OTHER "/> <setting name =" lazyLoadTriggerMethods "value =" equals, clone, hashCode, toString "/> </settings>View Code 4: typeAiases (alias)-Key Points

    In mapper. xml, many statement are defined. statement requires parameterType to specify the input parameter type, and resultType to specify the ing type of the output result.

    If the full path of the input type is not convenient for development when the type is specified, you can define aliases for the type specified by parameterType or resultType, and define aliases in mapper. xml to facilitate development.

    4.1.mybatis default supported aliases

    Alias

    Ing type

    _ 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 alias

    4.2.1: define a single alias (in SqlMapConfig. xml)  

    <! -- Alias definition: defines the type: Path of the type for a single alias; alias: alias --> <typeAliases> <typeAlias type = "com. mybatis. entity. user "alias =" user "/> </typeAliases>

    UserMapper. xml reference alias:

    <select id="findUserById" parameterType="int" resultType="user" >      select * from t_user where id=#{id}</select>

     4.2.2: Define aliases in batches (frequently used) 

    <! -- Batch alias definition: package: Specifies the package name. mybatis automatically scans the pojo class in the package and automatically defines the alias. the alias is the class name (either in upper or lower case) --> <typeAliases> <package name = "com. mybatis. entity "/>
    <Package name = "other packages"/>
    </TypeAliases>
    5. typeHandlers (type processor)

    In mybatis, jdbc and java types are converted using typeHandlers.

    In general, the type processor provided by mybatis meets daily needs and does not need to be customized.

    Mybatis supports type processors:

    Type Processor

    Java type

    JDBC Type

    BooleanTypeHandler

    Boolean, boolean

    Any compatible Boolean Value

    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 integer type

    LongTypeHandler

    Long, long

    Any compatible number or long integer

    FloatTypeHandler

    Float, float

    Any compatible numeric or single precision floating point type

    DoubleTypeHandler

    Double, double

    Any compatible numeric or Double Precision Floating Point Type

    BigDecimalTypeHandler

    BigDecimal

    Any compatible numeric or 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

    Arbitrary

    Other or unspecified types

    EnumTypeHandler

    Enumeration type

    VARCHAR-any compatible string type that is stored as code (rather than indexed ).

    6. mappers (ing configuration)

    6.1: load a single ing file using resource

    <! -- Load the ing file --> <mappers> <! -- Load a ing file at a time using the resource method --> <mapper resource = "sqlmap/User. xml "/> <mapper resource =" mapper/UserMapper. xml "/> </mappers>

    6.2: load a single ing file through the ER interface

    <! -- Use the mapper interface to load a single ing configuration file following certain specifications: you need to set the ER interface class name and mapper. the name of the xml ing file must be consistent and in a directory. The premise of the preceding rule is that the mapper proxy method is used; --> <mapper class = "com. mybatis. mapper. userMapper "/>

    According to the above specifications, put mapper. java and mapper. xml in a directory with the same name.

    6.3: Load mapper in batches (recommended)

    <! -- Load the er configuration file in batches. mybatis automatically scans the ER interface under the package to load according to certain specifications: The mapper Interface Class Name and mapper must be set. the name of the xml ing file must be consistent and in a directory. The premise of the preceding rule is that the mapper proxy method is used; --> <package name = "com. mybatis. mapper "/>

     

    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.