springJdbc 插入数据返回主键

public long addMsg(final SysMessage sysMessage){
		final String sql = "INSERT INTO sys_message (title,send_time,type,kugouIds,is_send) values(?,?,?,?,?) ";
//		jdbc.update(sql, sysMessage.getTitle(),sysMessage.getSendTime(),sysMessage.getType(), sysMessage.getKugouIds(),sysMessage.getIsSend() );
		KeyHolder keyHolder = new GeneratedKeyHolder();
		jdbc.update(new PreparedStatementCreator(){
		                   @Override
		                   public PreparedStatement createPreparedStatement(Connection conn) throws SQLException{
		                        PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
		                        ps.setString(1, sysMessage.getTitle());
		                        ps.setTimestamp(2, new Timestamp(sysMessage.getSendTime().getTime()));
		                        ps.setInt(3, sysMessage.getType());
		                        ps.setString(4, sysMessage.getKugouIds());
		                        ps.setInt(5, sysMessage.getIsSend());

		                        return ps;
		                    }
		                },
		                keyHolder);
		long msgId = keyHolder.getKey().longValue();
		return msgId;
	}

 使用org.springframework.jdbc.support.KeyHolder的getKey()方法

你可能感兴趣的:(springJdbc 插入数据返回主键)