Mybatis例子

1.批处理的操作,操作的时候需要设置连接信息带上参数:allowMultiQueries=true

<!--批量处理的操作:更新用户的属性内容-->
    <insert id="batchUpdateUserInfoData">
        <foreach collection="userIdList" item="userid" index="index" open="" close="" separator=";">
            UPDATE `${tableName}`
            SET
            <foreach item="value" index="key" collection="fieldObject.entrySet()" separator =",">
                `${key}` =
                <if test="value != null" >
                    #{value}
                </if>
                <if test="value == null" >
                    ''
                </if>
            </foreach>
            WHERE
            userid = #{userid}
        </foreach>
    </insert>

2.返回的JSONArray的结果集:

JSONArray selectPrizeGroupStatusByPrizeIdList(@Param("tableName") String tableName,@Param("prizeIdList") List prizeIdList);

xml的书写:

    <select id="selectPrizeGroupStatusByPrizeIdList" resultType="com.alibaba.fastjson.JSONObject">
        SELECT
          COUNT(*) as count,status,prize_id as prizeId
        FROM `${tableName}`
        WHERE
        1 = 1
        <if test="prizeIdList != null" >
          AND prize_id IN
            (
            <foreach collection="prizeIdList" item="onePrizeId" index="index" separator=",">
                ${onePrizeId}
            </foreach>
            )
        </if>
        GROUP BY status,prize_id
    </select>

 

 

 

3.List的查询操作:

<select id="xxDateToCount" resultType="com.alibaba.fastjson.JSONObject">
      SELECT
          `log_date` days,COUNT(id) numCount,type
      FROM `${tableName}`
      WHERE 1 =1
      <if test="typeList != null" >
          AND TYPE IN
          (
          <foreach collection="typeList" item="oneType" index="index" separator=",">
              ${oneType}
          </foreach>
          )
      </if>
      <if test="activityId != null" >
          AND activity_id = #{activityId,jdbcType=INTEGER}
      </if>
      <if test="channel != null and channel !=''" >
        AND channel = #{channel,jdbcType=VARCHAR}
      </if>
      <if test="startDate != null" >
        AND `log_date` <![CDATA[ >= ]]> #{startDate,jdbcType=VARCHAR}
      </if>
      <if test="endDate != null" >
        AND `log_date` <![CDATA[ <= ]]> #{endDate,jdbcType=VARCHAR}
      </if>
      GROUP BY days,TYPE
  </select>

相应的目标方法名称:

JSONArray xxDateToCount(@Param("tableName") String tableName,
                                              @Param("channel") String channel,
                                              @Param("startDate") Date startDate,
                                              @Param("endDate") Date endDate,
                                              @Param("activityId") Integer activityId,
                                              @Param("typeList") List<Integer> typeList);

4.batch批处理的操作:

<insert id ="insertMoreBatchDo">
    insert into `${tableName}`
    (
    `node_id`,`userid`,`num`,`status`,`custom_data`,`message`,
    <if test='type == "A"' >
      `os`,
    </if>
    <if test='type == "B"' >
      `fee`,
    </if>
    `created_at`,`updated_at`
    )
    values
    <foreach collection ="list" item="record" index= "index" separator =",">
      (
        #{record.nodeId,jdbcType=VARCHAR},
        #{record.userid,jdbcType=VARCHAR},
        #{record.num,jdbcType=VARCHAR},
        #{record.status,jdbcType=INTEGER},
        #{record.customData,jdbcType=LONGVARCHAR},
        #{record.message,jdbcType=VARCHAR},
        <if test='type == "A"' >
          <choose>
            <when test='record.os != null'>
              #{record.os,jdbcType=VARCHAR},
            </when>
            <otherwise>
              "",
            </otherwise>
          </choose>
        </if>
        <if test='type == "B"' >
          <choose>
            <when test='record.os != null'>
              #{record.fee,jdbcType=INTEGER},
            </when>
            <otherwise>
              '0',
            </otherwise>
          </choose>
        </if>
        #{record.createdAt,jdbcType=TIMESTAMP},
        #{record.updatedAt,jdbcType=TIMESTAMP}
      )
    </foreach >
  </insert>



Mapper方法:
int insertMoreBatchDo(@Param("tableName") String tableName, @Param("type") String type, @Param("list") List<Bean> list);

 

5.left join + 分页查询的操作( like 用bind标签来进行组拼):

<resultMap id="prizeDTO" type="com.xxxx.PrizeDTO" extends="BaseResultMap" >
        <result column="stock" property="stock" jdbcType="INTEGER" />
        <result column="used" property="used" jdbcType="INTEGER" />
        <result column="owned" property="owned" jdbcType="BIT" />
</resultMap>

<select id="selectByList"  resultMap="prizeDTO">
        SELECT
          <include refid="prize_column" />
          ,
        d.app_id,d.merchant_id,d.used,d.stock,d.owned
        FROM prize_distributes d LEFT JOIN prizes p
        ON p.id=d.prize_id
        WHERE d.app_id=#{appId,jdbcType=INTEGER}
        AND d.merchant_id=#{merchantId,jdbcType=INTEGER}
        AND p.deleted_at is NULL
        <if test="status != null and status == 'valid'" >
            AND
            (p.from_date <![CDATA[ <= ]]>  now()
            AND p.to_date <![CDATA[ >= ]]> now()
            OR (p.from_date IS NULL AND p.to_date IS NULL))
        </if>
        <if test="status != null and status == 'expired'" >
            AND p.to_date <![CDATA[ < ]]> now()
        </if>
        <if test="owned != null" >
            AND d.owned = #{owned}
        </if>
        <if test="type != null and type !=''" >
            AND p.type = #{type}
        </if>
        <if test="name != null and name !=''" >
            <bind name="pattern" value="'%'+name+'%'"/>
            AND p.name LIKE  #{pattern}
        </if>
        ORDER BY p.created_at DESC
    </select>

使用pageHelper插件来进行操作:

 PageHelper.startPage(page, pageSize);
 List<PrizeDTO> list = prizeMapper.selectByList(appId, merchantId, owValue, type, status, name);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis是一个功能强大、灵活且易于使用的开源持久化框架,它是一个基于Java开发的持久层框架,简化了数据库操作的编写过程,提供了一种将SQL语句和Java代码分离的方式。 以下是一个MyBatis的入门例子: 1. 首先,在项目的依赖管理工具(如Maven)中添加MyBatis的依赖项,以便能够引入MyBatis的相关类库。 2. 创建一个实体类,用于映射数据库中的表。该类需要与数据库表的字段一一对应,并提供相应的setter和getter方法。 3. 创建一个Mapper接口,其中定义了与数据库操作相关的方法。例如,可以编写一个方法,用于查询数据库表中的数据。 4. 在Mapper接口中,使用注解或XML文件来定义SQL语句。例如,可以使用@Select注解来指定一个查询语句,并通过@Results注解来指定将查询结果映射到实体类的哪些字段上。 5. 创建一个Mapper XML文件,其中定义了SQL语句的具体内容。例如,可以编写一个<select>标签用于查询语句,并使用<resultMap>标签来指定结果的映射。 6. 在MyBatis的配置文件中,配置数据源和连接池等相关信息,并将Mapper接口的映射加入到配置中。配置文件可以为XML文件或使用Java代码进行配置。 7. 在应用程序中,通过MyBatis的API来获取SqlSession实例,并使用SqlSession来执行数据库操作。例如,可以通过SqlSession的selectOne()方法来执行查询操作,并传入Mapper接口的方法名和参数。 8. 最后,关闭SqlSession。 通过以上步骤,就可以使用MyBatis进行数据库操作。MyBatis的优势在于可以灵活地控制SQL语句,提供了多种查询方式和参数传递方式,且能够从SQL中获取结果映射到实体类中。同时,MyBatis的配置简单明了,易于学习和使用。因此,MyBatis在Java开发中被广泛运用于数据库操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值