window.ENTITIES={'/api/snippets/java/spring%20boot%202%20-%20jdbctemplate%20update%20query%20example%20to%20mysql%20database':[{"result":true,"message":null,"batch":{"type":"java","name":"spring boot 2 - jdbctemplate update query example to mysql database","items":[{"id":"Dg3XOD","type":"java","name":"Spring Boot 2 - JdbcTemplate UPDATE query example to MySQL database","content":"package com.example.demo;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.MediaType;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.jdbc.core.PreparedStatementCreator;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.*;\n\nimport java.sql.Connection;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\nimport java.util.Collections;\n\n@Controller\npublic class UsersController {\n\n @Autowired\n private JdbcTemplate jdbcTemplate;\n\n // POST http://localhost:8080/api/users/1/update\n // echo '{\"name\":\"john\",\"email\":\"john@email.com\"}' | curl -X POST -H \"Content-Type: application/json\" -d @- http://localhost:8080/api/users/1/update\n //\n @PostMapping(\n value = \"/api/users/{id}/update\",\n consumes = MediaType.APPLICATION_JSON_VALUE,\n produces = MediaType.APPLICATION_JSON_VALUE\n )\n @ResponseBody\n public Object updateUser(\n @PathVariable(\"id\") Long userId,\n @RequestBody UserEntity userEntity\n ) throws SQLException {\n String query = \"UPDATE `users` SET `name` = ?, `email` = ? WHERE `id` = ?\";\n PreparedStatementCreator statementCreator = (Connection connection) -> {\n PreparedStatement preparedStatement = connection.prepareStatement(query);\n preparedStatement.setString(1, userEntity.getName());\n preparedStatement.setString(2, userEntity.getEmail());\n preparedStatement.setLong(3, userId);\n return preparedStatement;\n };\n int updatesCount = this.jdbcTemplate.update(statementCreator);\n return Collections.singletonMap(\"result\", updatesCount == 1);\n }\n}\n\n\n// DATABASE PREPARATION:\n\n/*\n\n CREATE DATABASE `example_db`\n\n\n CREATE TABLE `users` (\n `id` BIGINT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n `name` VARCHAR(100) NOT NULL,\n `email` VARCHAR(255) NOT NULL,\n PRIMARY KEY (`id`)\n )\n ENGINE=InnoDB;\n\n\n INSERT INTO `users`\n (`name`, `email`)\n VALUES\n ('Chris', 'chris@mail.com'),\n ('Kate', 'kate@mail.com'),\n ('Denis', 'denis@mail.com');\n\n*/","source":"","author":{"id":"Ro42dD","name":"Creg","avatar":"1667335677213__Ro42dD__w40px_h40px.jpg","points":9600,"role":"ADMIN"},"creationTime":1652572825000,"updateTime":1652572846000,"removalTime":null}]}}]};