MyBatis: mybatisConfig.xml configuration file

The content and order of the configuration in mybatisConfig.xml are as follows:

  • properties
  • settings (global configuration parameters)
  • typeAliases (type aliases)
  • typeHandlers (type processors)
  • objectFactory
  • plugins
  • environments (environment collection attribute object)
    • environment (environment sub-attribute object)
      • transactionManager
      • dataSource (data source)
  • mappers

properties

MybatisConfig.xml can refer to the configuration information in the java property file as follows:

Define the db.properties file under the classpath

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/data
jdbc.username=root
jdbc.password=root

mybatisConfig.xml is quoted as follows

<properties resource="db.properties"></properties>
<environments default="development">
	<environment id="development">
		<transactionManager type="JDBC" />
		<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 the properties in the following order:

  • The properties defined in the properties element body are read first.
  • Then it will read the attribute loaded by resource or url in the properties element, and it will overwrite the attribute of the same name that has been read.
  • Finally read the attribute passed by parameterType, it will overwrite the attribute of the same name that has been read.

Therefore, the attribute passed through parameterType has the highest priority, followed by the attribute loaded by resource or url, and the lowest priority is the attribute defined in the properties element body.

settings

Mybatis global configuration parameters, global parameters will affect the running behavior of mybatis. An example of a fully configured settings element is as follows:

<settings>
  <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="autoMappingUnknownColumnBehavior" value="WARNING"/>
  <setting name="defaultExecutorType" value="SIMPLE"/>
  <setting name="defaultStatementTimeout" value="25"/>
  <setting name="defaultFetchSize" value="100"/>
  <setting name="safeRowBoundsEnabled" value="false"/>
  <setting name="mapUnderscoreToCamelCase" value="false"/>
  <setting name="localCacheScope" value="SESSION"/>
  <setting name="jdbcTypeForNull" value="OTHER"/>
  <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
Setting parameters description Effective value Defaults
cacheEnabled Globally turn on or off any cache that has been configured by all mappers in the configuration file. true | false TRUE
lazyLoadingEnabled Global switch for delayed loading. When turned on, all associated objects will be lazily loaded. You can set the fetchType property to override the on-off status of the item in a specific association. true | false FALSE
aggressiveLazyLoading When turned on, any method call will load all properties of the object. Otherwise, each property will be loaded as needed (refer to lazyLoadTriggerMethods). true | false false (true in ≤3.4.1)
multipleResultSetsEnabled Whether to allow a single statement to return multiple result sets (requires compatible drivers). true | false TRUE
useColumnLabel Use column labels instead of column names. Different drivers will have different performances in this regard. For details, please refer to the relevant driver documentation or test these two different modes to observe the results of the drivers used. true | false TRUE
useGeneratedKeys To allow JDBC to support automatic generation of primary keys, driver compatibility is required. If set to true, this setting forces the use of automatically generated primary keys, although some drivers are not compatible but can still work normally (such as Derby). true | false FALSE
autoMappingBehavior Specify how MyBatis should automatically map columns to fields or properties. NONE means cancel automatic mapping; PARTIAL will only automatically map result sets that do not define nested result set mappings. FULL will automatically map any complex result set (whether or not nested). NONE, PARTIAL, FULL PARTIAL
autoMappingUnknownColumnBehavior Specify the behavior of automatically discovering the target unknown column (or unknown attribute type). NONE, WARNING, FAILING NONE
NONE: No response
WARNING: Output reminder log ('org.apache.ibatis.session.AutoMappingUnknownColumnBehavior' log level must be set to WARN)
FAILING: Mapping failed (throw SqlSessionException)
defaultExecutorType Configure the default actuator. SIMPLE is an ordinary executor; the REUSE executor will reuse prepared statements; the BATCH executor will reuse statements and perform batch updates. SIMPLE REUSE BATCH SIMPLE
defaultStatementTimeout Set the timeout period, which determines the number of seconds the driver waits for a response from the database. Any positive integer Not Set (null)
defaultFetchSize Set a hint value for the number of fetched result sets (fetchSize). This parameter can only be overridden in the query settings. Any positive integer Not Set (null)
safeRowBoundsEnabled Allow pagination (RowBounds) in nested statements. Set to false if allowed. true | false FALSE
safeResultHandlerEnabled Allow paging (ResultHandler) in nested statements. Set to false if allowed. true | false TRUE
mapUnderscoreToCamelCase Whether to enable automatic camel case naming rule (camel case) mapping, that is, a similar mapping from the classic database column name A_COLUMN to the classic Java property name aColumn. true | false FALSE
localCacheScope MyBatis uses Local Cache to prevent circular references and accelerate repeated nested queries. The default value is SESSION, in which case all queries executed in one session will be cached. If the setting value is STATEMENT, the local session is only used for statement execution, and different calls to the same SqlSession will not share data. SESSION | STATEMENT SESSION
jdbcTypeForNull When no specific JDBC type is provided for the parameter, specify the JDBC type for the null value. Some drivers need to specify the JDBC type of the column. In most cases, the general type can be used directly, such as NULL, VARCHAR, or OTHER. JdbcType constants. Most of them are: NULL, VARCHAR and OTHER OTHER
lazyLoadTriggerMethods The method of specifying which object triggers a lazy load. A comma-separated list of methods. equals,clone,hashCode,toString
defaultScriptingLanguage Specify the default language for dynamic SQL generation. 一个类型别名或完全限定类名。 org.apache.ibatis.scripting.xmltags.XMLLanguageDriver
defaultEnumTypeHandler 指定 Enum 使用的默认 TypeHandler 。 (从3.4.5开始) 一个类型别名或完全限定类名。 org.apache.ibatis.type.EnumTypeHandler
callSettersOnNulls 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这对于有 Map.keySet() 依赖或 null 值初始化的时候是有用的。注意基本类型(int、boolean等)是不能设置成 null 的。 true | false FALSE
returnInstanceForEmptyRow 当返回行的所有列都是空时,MyBatis默认返回null。 当开启这个设置时,MyBatis会返回一个空实例。 请注意,它也适用于嵌套的结果集 (i.e. collectioin and association)。(从3.4.2开始) true | false FALSE
logPrefix 指定 MyBatis 增加到日志名称的前缀。 任何字符串 Not set
logImpl 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING Not set
proxyFactory 指定 Mybatis 创建具有延迟加载能力的对象所用到的代理工具。 CGLIB | JAVASSIST JAVASSIST (MyBatis 3.3 or above)
vfsImpl 指定VFS的实现 自定义VFS的实现的类全限定名,以逗号分隔。 Not set
useActualParamName 允许使用方法签名中的名称作为语句参数名称。 为了使用该特性,你的工程必须采用Java 8编译,并且加上-parameters选项。(从3.4.1开始) true | false TRUE
configurationFactory 指定一个提供Configuration实例的类。 这个被返回的Configuration实例用来加载被反序列化对象的懒加载属性值。 这个类必须包含一个签名方法static Configuration getConfiguration(). (从 3.2.3 版本开始) 类型别名或者全类名. Not set

 typeAliases(类型别名)

别名

映射的类型

_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

object

Object

map

Map

hashmap

HashMap

list

List

arraylist

ArrayList

collection

Collection

iterator

Iterator

自定义别名:

<typeAliases>
	<!-- 单个别名定义 -->
	<typeAlias alias="user" type="org.haiwen.entity.User"/>
	<!-- 批量别名定义,扫描整个包下的类,别名为类名(首字母大写或小写都可以) -->
	<package name="org.haiwen.entity"/>
	<package name="其它包"/>
</typeAliases>

typeHandlers(类型处理器)

无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。

类型处理器 Java 类型 JDBC 类型
BooleanTypeHandler java.lang.Boolean, boolean 数据库兼容的 BOOLEAN
ByteTypeHandler java.lang.Byte, byte 数据库兼容的 NUMERIC 或 BYTE
ShortTypeHandler java.lang.Short, short 数据库兼容的 NUMERIC 或 SHORT INTEGER
IntegerTypeHandler java.lang.Integer, int 数据库兼容的 NUMERIC 或 INTEGER
LongTypeHandler java.lang.Long, long 数据库兼容的 NUMERIC 或 LONG INTEGER
FloatTypeHandler java.lang.Float, float 数据库兼容的 NUMERIC 或 FLOAT
DoubleTypeHandler java.lang.Double, double 数据库兼容的 NUMERIC 或 DOUBLE
BigDecimalTypeHandler java.math.BigDecimal 数据库兼容的 NUMERIC 或 DECIMAL
StringTypeHandler java.lang.String CHAR, VARCHAR
ClobReaderTypeHandler java.io.Reader -
ClobTypeHandler java.lang.String CLOB, LONGVARCHAR
NStringTypeHandler java.lang.String NVARCHAR, NCHAR
NClobTypeHandler java.lang.String NCLOB
BlobInputStreamTypeHandler java.io.InputStream -
ByteArrayTypeHandler byte[] 数据库兼容的字节流类型
BlobTypeHandler byte[] BLOB, LONGVARBINARY
DateTypeHandler java.util.Date TIMESTAMP
DateOnlyTypeHandler java.util.Date DATE
TimeOnlyTypeHandler java.util.Date TIME
SqlTimestampTypeHandler java.sql.Timestamp TIMESTAMP
SqlDateTypeHandler java.sql.Date DATE
SqlTimeTypeHandler java.sql.Time TIME
ObjectTypeHandler Any OTHER 或未指定类型
EnumTypeHandler Enumeration Type VARCHAR-任何兼容的字符串类型,存储枚举的名称(而不是索引)
EnumOrdinalTypeHandler Enumeration Type 任何兼容的 NUMERIC 或 DOUBLE 类型,存储枚举的索引(而不是名称)。
InstantTypeHandler java.time.Instant TIMESTAMP
LocalDateTimeTypeHandler java.time.LocalDateTime TIMESTAMP
LocalDateTypeHandler java.time.LocalDate DATE
LocalTimeTypeHandler java.time.LocalTime TIME
OffsetDateTimeTypeHandler java.time.OffsetDateTime TIMESTAMP
OffsetTimeTypeHandler java.time.OffsetTime TIME
ZonedDateTimeTypeHandler java.time.ZonedDateTime TIMESTAMP
YearTypeHandler java.time.Year INTEGER
MonthTypeHandler java.time.Month INTEGER
YearMonthTypeHandler java.time.YearMonth VARCHAR or LONGVARCHAR
JapaneseDateTypeHandler java.time.chrono.JapaneseDate DATE

mappers(映射器)

Mapper配置的几种方法:

使用相对于类路径的资源:<mapper resource=" " />
如:<mapper resource="sqlmap/User.xml" /> 
使用完全限定路径:<mapper url=" " />
如:<mapper url="file:///D:\workspace_spingmvc\mybatis_01\config\sqlmap\User.xml" />
使用mapper接口类路径:<mapper class=" " />
如:<mapper class="cn.itcast.mybatis.mapper.UserMapper"/>
注意:此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中。
注册指定包下的所有mapper接口:<package name=""/>
如:<package name="cn.itcast.mybatis.mapper"/>
注意:此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中。
发布了202 篇原创文章 · 获赞 37 · 访问量 3万+

Guess you like

Origin blog.csdn.net/lovecuidong/article/details/101065516