#1
This guide shows how to use ClickHouse in Spring Boot applications to store and query IoT data efficiently.

1. Create IoT Table in ClickHouse

CREATE TABLE iot_data (
    device_id String,
    ts DateTime,
    temperature Float64,
    humidity Float64
) ENGINE = MergeTree()
ORDER BY (device_id, ts);

2. Insert IoT Data

INSERT INTO iot_data (device_id, ts, temperature, humidity) VALUES
('sensor-1', now(), 23.5, 60.1),
('sensor-2', now(), 25.2, 55.8);

3. Spring Boot Entity

public class IoTData {
    private String deviceId;
    private LocalDateTime ts;
    private Double temperature;
    private Double humidity;
}

4. Save Data with JdbcTemplate

jdbcTemplate.update(
    "INSERT INTO iot_data (device_id, ts, temperature, humidity) VALUES (?, ?, ?, ?)",
    data.getDeviceId(), data.getTs(), data.getTemperature(), data.getHumidity()
);

5. Query Recent Sensor Data

List<Map<String, Object>> recent = jdbcTemplate.queryForList(
    "SELECT * FROM iot_data WHERE device_id = 'sensor-1' ORDER BY ts DESC LIMIT 10"
);

6. Expose REST API

@RestController
@RequestMapping("/iot")
public class IoTController {
    @GetMapping("/latest/{deviceId}")
    public List<Map<String, Object>> getLatest(@PathVariable String deviceId) {
        return jdbcTemplate.queryForList(
            "SELECT * FROM iot_data WHERE device_id=? ORDER BY ts DESC LIMIT 10", deviceId
        );
    }
}

image quote pre code