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

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...