postgreSQL插入语句返回主键

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

 public  S save(S entity) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        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());
        getNamedParameterJdbcTemplate().update(sql, term, keyHolder);
        List keyList = keyHolder.getKeyList();
        if (keyList != null && keyList.size() > 0) {
            Map map = (Map) keyList.get(0);
            entity.setId(Long.parseLong(String.valueOf(map.get("id"))));
        }
        return entity;
    }
 利用KeyHolder即可返回自动增长的主键!

你可能感兴趣的:(JAVAweb)