mybatis配置注意事项

文章目录

  • mybatis配置注意事项
    • Mapper文件配置
      • resultMap配置顺序
      • 使用枚举类型

mybatis配置注意事项

##mybatis-config.xml
注意配置节点顺序

properties
settings
typeAliases
typeHandlers
objectFactory
objectWrapperFactory
plugins
environments
databaseIdProvider
mappers

如果不按顺序报异常

Caused by: org.xml.sax.SAXParseException(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)"。

Mapper文件配置

resultMap配置顺序

 <resultMap>
        <constructor>
            <idArg/>
            <arg/>
        constructor>
        <id/>
        <result/>
        <association property=""/>
        <collection property=""/>
        <discriminator javaType="">
            <case value="">case>
        discriminator>
    resultMap>

官方文档给的例子


<resultMap id="detailedBlogResultMap" type="Blog">
  <constructor>
    <idArg column="blog_id" javaType="int"/>
  constructor>
  <result property="title" column="blog_title"/>
  <association property="author" javaType="Author">
    <id property="id" column="author_id"/>
    <result property="username" column="author_username"/>
    <result property="password" column="author_password"/>
    <result property="email" column="author_email"/>
    <result property="bio" column="author_bio"/>
    <result property="favouriteSection" column="author_favourite_section"/>
  association>
  <collection property="posts" ofType="Post">
    <id property="id" column="post_id"/>
    <result property="subject" column="post_subject"/>
    <association property="author" javaType="Author"/>
    <collection property="comments" ofType="Comment">
      <id property="id" column="comment_id"/>
    collection>
    <collection property="tags" ofType="Tag" >
      <id property="id" column="tag_id"/>
    collection>
    <discriminator javaType="int" column="draft">
      <case value="1" resultType="DraftPost"/>
    discriminator>
  collection>
resultMap>

使用枚举类型

MyBatis内置了两个枚举转换器分别是:org.apache.ibatis.type.EnumTypeHandler(对应enum.name)和org.apache.ibatis.type.EnumOrdinalTypeHandler(对应enum.ordinal)。

< result column="type" property="type" typeHandler="org.apache.ibatis.type.EnumOrdinalTypeHandler" />

插入语句

INSERT INTO table (id,type) VALUES (#{id},${type==null?'null':type.ordinal()})

还可以自定义类型转换器具体方法参见
MyBatis中如何优雅的使用枚举详解

你可能感兴趣的:(mybatis)