MyBatis-plus BaseMapper 自定义insert方法 插入自增ID对象及其他无关该表的字段

 需求:做一个多表查询过滤后的Insert SQL,需要获取insert后的自增ID,并且该自定义的BaseMapper能够传入除Entity(下方代码为Points)以外的`其余变量`(其他表的字段,下方代码为type)

Naive Solution:在实体类(Points)中直接添加`其余字段`(type,不在Points表中)。但是如果相似的Insert SQL增多后,会不断污染该实体类的字段,降低代码的可维护性。

因此,本文直接对自定义的BaseMapper子类Insert方法扩展形式参数,只需在@Insert中指明某些字段为Points对象的成员变量即可

public interface PointsMapper extends BaseMapper<Points> {


    /**
     * 每日0点后可插入积分,乐观锁
     * @param points 积分信息
     *               userId 用户id
     *               points 积分额度
     * @param type 积分类型
     * @return 插入行数
     */
    @Insert("INSERT INTO points (user_id, points, start_time, end_time, create_time, deleted)\n" +
            "SELECT #{points.userId}, #{points.points}, NOW(), DATE_ADD(NOW(), INTERVAL 1 YEAR), NOW(), 0\n" +
            "WHERE NOT EXISTS (\n" +
            "    SELECT 1\n" +
            "    FROM `points_log`\n" +
            "    WHERE user_id = #{points.userId} AND type = #{type}\n" +
            "      AND DATE(create_time) = CURDATE()\n" +
            ");")
    @Options(useGeneratedKeys = true, keyProperty = "points.id", keyColumn = "id")
    Integer insertPointsOnceDay(@Param("points") Points points, @Param("type") Integer type);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值