spring jdbcTemplate 插入对象返回主键值

  /**
     * 插入一个对象,并返回这个对象的自增id
     * @param obj
     * @return
     */
    public  int insertObjectAndGetAutoIncreaseId(T obj) {
        final String sql = BeanOperator.getSqlByObject(SqlTypes.INSERT, obj);
        
		KeyHolder keyHolder = new GeneratedKeyHolder();
        int autoIncId = 0;
        
        jdbcTemplate.update(new PreparedStatementCreator() {
    		public PreparedStatement createPreparedStatement(Connection con)
    				throws SQLException {
    			PreparedStatement ps = con.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
    			return ps;
    		}
    	}, keyHolder);

        autoIncId = keyHolder.getKey().intValue();
    	
        return autoIncId;
    }

你可能感兴趣的:(3_spring)