微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

postgreSQL插入语句返回主键

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即可返回自动增长的主键!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐