Mybatis使用技巧

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fengshizty/article/details/49669663

以下就总结一下Mybatis的使用中的一些不太注意的技巧,算是Mybatis的总结笔

1、插入时主键返回

     我们向数据库插入一条记录是,使用Mybatis的<insert>是无法返回插入的主键的,而我们需要这个刚插入的主键,可以如下返回

         自增主键:使用last_insert_id()查询刚插入的key的id,该方法需要和insert配合使用,是插入之后获取。

         result返回的是插入成功条数,而主键id返回到CourseInfo的id属性中

        

<insert id="insert" parameterType="org.andy.shop.model.CourseInfo" >
    insert into course_info (id, cname, caddress)
    values (#{id,jdbcType=INTEGER}, #{cname,jdbcType=VARCHAR}, #{caddress,jdbcType=VARCHAR})
  
     <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
       select last_insert_id()
     </selectKey>
  </insert>


或者如下的写法更简单:

<insert id="insert" parameterType="org.andy.shop.model.CourseInfo" useGeneratedKeys="true" keyProperty="id">
    insert into course_info (id, cname, caddress
      )
    values (#{id,jdbcType=INTEGER}, #{cname,jdbcType=VARCHAR}, #{caddress,jdbcType=VARCHAR}
      )
  </insert>


       非自增主键:但我们的ID为uuid字符类型的32为长度时,我们使用mysql的uuid()查询主键,是在查询之后在插入。

<insert id="insert" parameterType="org.andy.shop.model.CourseInfo" >
    <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
      select uuid()
    </selectKey>
    insert into course_info (id, cname, caddress)
    values (#{id,jdbcType=VARCHAR}, #{cname,jdbcType=VARCHAR}, #{caddress,jdbcType=VARCHAR})
  </insert>
 

    使用oracle数据库时:使用 序列名.nextval()函数获取。


2、别名的使用

      一般定义别名,在Mapper配置的可以使用别名,定义单个别名如下

<configuration>
<typeAliases>
 <typeAlias type="org.andy.shop.model.CourseUserInfo" alias="CourseUserInfo"/>
</typeAliases>
</configuration>

      自动定义别名:Mybatis 将自动扫描包名下的po,别名就是类名(大写小写都可以)

<typeAliases>
  <package name="org.andy.shop.model"/>
</typeAliases>


3、动态sql使用

      一般我们会涉及多个动态查询条件,一般我们是通过 where 1 = 1,这样可以处理where后面对应全空的情况,我们可以使用<where>标签,该标签可以自动处理。

        <where>
	  <if test="name != nulll">
	     and name like concat('%',trim(#{name,jdbcType=VARCHAR}),'%') 
	  </if>
	</where>


4、sql片段

     我们可以将常用的重复的sql定义sql片段

    定义如下:

    

<sql id="Base_Column_List" >
    id, name, url, priority, logo, img
  </sql>

   引用该片段如下:

  

<include refid="Base_Column_List" />

5、关联查询

一对一关联查询

       

        一对多关联查询


6、延迟加载

       延迟加载:先从单表查询,在需要时从关联表查询,可以大大的提高数据库性能,单表查询的性能要快于多表联合查询的速度。

而Mybatis的associate、collection就支持延迟加载功能。

    

    开启延迟加载:

      需要在Mybatis的核心配置文件中配置configuration开启setting两个配置

      

     设置lazyLoadingEnabled为true, aggressiveLazyLoading为false


未完待续。

      

       mybatis文档地址:http://www.mybatis.org/mybatis-3/zh/index.html

猜你喜欢

转载自blog.csdn.net/fengshizty/article/details/49669663