Postgresql 创建SEQUENCE,Springboot中使用KeyHolder
项目中使用到JdbcTemplate中的KeyHolder,代码如下:
String sql = "insert into web_users(username, password, phone, company) values(?,?,?,?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); getJdbcTemplate().update( con -> { PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, user.getUsername()); ps.setString(2, user.getPassword()); ps.setString(3, user.getPhone()); ps.setString(4, user.getCompany()); return ps; }, keyHolder); int userid = (int) keyHolder.getKeys().get("id"); return userid;
当执行到这段代码的时候会报错
org.postgresql.util.PSQLException: ERROR: null value in column "id" violates not-null constraint
考虑到应该是id字段默认值有问题,应该设置为 nextval('demo_users_seq'::regclass) ,
需要创建
SEQUENCE
CREATE SEQUENCE web_users_seq INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 START 1;
设置完毕之后再次尝试,可以成功插入值。