Mybatis实例整理记录

2019-02-12  本文已影响0人  怕冻的南方人

前言

这篇博文收录了我平时工作和学习中关于Mybatis使用中的常见的一些操作,包括配置问题和具体mapperXml的编写等,用于回顾和技术积累。

配置问题收录

233

mapperXml收录

1. 为插入的一条数据手动生成主键并将其返回

业务代码示例

// dao文件的目标接口
public interface ImageDao {
    // 返回值int为本次操作影响的数据条数,返回值0代表插入失败
    public int saveIgnorePK(Image image);
}

// mapper映射的实现方法1,通过中间表建立子查询(MySQL特殊)
<insert id="saveIgnorePK" useGeneratedKeys="true" keyProperty="imageId" >
    INSERT INTO t_image( image_id, image_name, image_type, image_size, image_location,
                         like_count, download_count, uploader_id, upload_time, update_time)
    VALUES ( (select id from (select max(image_id)+1 as id from t_image) as a),
             #{imageName}, #{imageType}, #{imageSize}, #{imageLocation}, 
             #{likeCount}, #{downloadCount}, #{uploaderId}, #{uploadTime}, #{updateTime})
</insert>

// mapper映射的实现方法2,使用<selectKey>的通用解决方案
<insert id="saveIgnorePK" useGeneratedKeys="true" keyProperty="imageId" >
    <!-- 这里的id会覆盖原参数的 -->
    <selectKey order="BEFORE" resultType="java.lang.Integer" keyProperty="imageId" statementType="">
        select max(image_id)+1 from t_image;
    </selectKey>
    INSERT INTO t_image( image_id, image_name, image_type, image_size, image_location,
                         like_count, download_count, uploader_id, upload_time, update_time)
    VALUES ( #{imageId}, #{imageName}, #{imageType}, #{imageSize}, #{imageLocation},
             #{likeCount}, #{downloadCount}, #{uploaderId}, #{uploadTime}, #{updateTime});
</insert>

测试代码示例

public void testSQL(){
    Image image = new Image();
    image.setAll();
      
    Integer res = imageDao.saveIgnoreAndReturnPK(image);
    System.out.println(res);  // 输出 1
    System.out.println(image.getImageId());  // 输出 10071
}

相关解析

业务SQL收录

233

上一篇 下一篇

猜你喜欢

热点阅读