04 注解使用

Wu Jun 2019-01-05 17:03:29
07 数据库 > 02 MyBatis

1 Provider

Mapper 接口

@InsertProvider、@DeleteProvider、@SelectProvider

Provider 注解,属性 type = Provider 类和 method = Provider 类中的方法

@Repository
public interface InterMsgMapper {
    @DeleteProvider(type = InterMsgProvider.class, method = "delete")
    int delete(Integer actionType, Integer targetType, Long actionId);
}
Provider 类实现
public class InterMsgProvider {
    public String delete(Integer actionType, Integer targetType, Long actionId) {
        return "delete from inter_msg where id <> 0 and action_type= " + actionType
                + " and target_type = " + targetType
                + " and action_id = " + actionId;
    }
}

2 循环

https://mybatis.org/mybatis-3/zh/dynamic-sql.html

foreach

@Update({"<script>",
            "update goods set status = #{status,jdbcType=TINYINT} where id in ",
            "<foreach item='goodsId' index='index' collection='goodsIds' open='(' separator=',' close=')'>",
            "#{goodsId,jdbcType=BIGINT}",
            "</foreach>",
            "</script>"})
int updateGoodsStatus(@Param("goodsIds") List<Long> goodsIds, @Param("status") Byte status);

if

    @Update({"<script>",
            "update t_sync_time ",
            " set updateTime = #{beginTime}",
            "<if test='isAll == true'>",
            ", allTime = #{beginTime}",
            "</if>",
            ", manualAll = 0",
            " where id = #{id}",
            "</script>"})
    int updateById(@Param("id") int id, @Param("isAll") boolean isAll, @Param("beginTime") String beginTime);

if + foreach

@Select({"<script>",
        " select sku.innerId from t_cps_sku sku INNER JOIN t_ams_account account on sku.warehouseId = account.warehouseId ",
        " where sku.updateTime >= #{updateTime}",
        "<if test='warehouseIds != null and warehouseIds.size() > 0'>",
            " or sku.warehouseId in ",
            "<foreach item='warehouseId' index='index' collection='warehouseIds' open='(' separator=',' close=')'>",
            "#{warehouseId}",
            "</foreach>",
        "</if>",
        "</script>"})
List<Long> getCpsSkuAccountByupdateTime(@Param("updateTime") Date updateTime, @Param("warehouseIds") List<Integer> warehouseIds);

3 @Options 注解

获取主键

@Options注解中默认主键字段名为id,可用keyProperty和keyColumn自定义,把数据从keyColumn字段放到传入对象的keyProperty成员变量里面。

@Insert("insert into instance (infos)"
                    + " ("
                    + " @{infos},"
                    + " NOW()"
                    + ")")
@Options(useGeneratedKeys = true, keyProperty = "instanceId", keyColumn = "instance_id")
int addInstance(Instance instance);
设置缓存

@Option注解还有一下选项: