需求:做一个多表查询过滤后的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);
}