加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgreSQL插入语句返回主键

发布时间:2020-12-13 17:15:42 所属栏目:百科 来源:网络整理
导读:SprimgMVCJDBC 操作 postgreSql的时候,由于主键是自动增长的,所以插入时不需要制定id,但如何返回自动增长的主键呢? public S extends AttachmentEnt S save(S entity) { span style="color:#ff0000;"KeyHolder keyHolder = new GeneratedKeyHolder();/sp

SprimgMVCJDBC 操作postgreSql的时候,由于主键是自动增长的,所以插入时不需要制定id,但如何返回自动增长的主键呢?

 public <S extends AttachmentEnt> S save(S entity) {
        <span style="color:#ff0000;">KeyHolder keyHolder = new GeneratedKeyHolder();</span>
        String sql = "INSERT INTO wl_ent_attachment (ent_id," +
                "storage_type,key,mime_type,name,label,description,created_by," +
                "created_time,updated_by,edit_time,status) " +
                "VALUES (:ent_id,:storage_type,:key,:mime_type,:name,:label," +
                ":description,:created_by,:created_time,:updated_by,:edit_time,:status)";
        MapSqlParameterSource term = new MapSqlParameterSource();
        term.addValue("ent_id",entity.getEntId());
        term.addValue("storage_type",entity.getStorageType());
        term.addValue("key",entity.getKey());
        term.addValue("mime_type",entity.getMimeType());
        term.addValue("name",entity.getName());
        term.addValue("label",entity.getLabel());
        term.addValue("description",entity.getDescription());
        term.addValue("created_by",entity.getCreatedBy());
        term.addValue("created_time",entity.getCreatedTime());
        term.addValue("updated_by",entity.getUpdatedBy());
        term.addValue("edit_time",entity.getEditTime());
        term.addValue("status",entity.getStatus());
        <span style="color:#ff0000;">getNamedParameterJdbcTemplate().update(sql,term,keyHolder);</span>
        List keyList = keyHolder.getKeyList();
        if (keyList != null && keyList.size() > 0) {
            Map map = (Map) keyList.get(0);
            <span style="color:#ff0000;">entity.setId(Long.parseLong(String.valueOf(map.get("id"))));</span>
        }
        return entity;
    }
利用KeyHolder即可返回自动增长的主键!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读