postgreSQL插入语句返回主键

前端之家收集整理的这篇文章主要介绍了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即可返回自动增长的主键!

猜你在找的Postgre SQL相关文章