spring jdbcTemplate 插入对象返回主键值

2021-09-23 11:05:14 浏览数 (1)

代码语言:javascript复制
public int addClifford(Clifford clifford) {
    String sql = "insert into t_user_clifford(mobile,last_activity_date,clifford_count,is_share)values(?,?,?,?)";
    int idResult = 0;
    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplateActivityWrite.update(new PreparedStatementCreator() {
        @Override
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
            ps.setObject(1,clifford.getMobile());
            ps.setObject(2,clifford.getLastActivityDate());
            ps.setObject(3,clifford.getCliffordCount());
            ps.setObject(4,clifford.getIsShare());
            return ps;
        }
    },keyHolder);
    idResult = keyHolder.getKey().intValue();
    return idResult;
}

0 人点赞