[Edit]
+
0
-
0

Spring Boot 2 - JdbcTemplate INSERT query example to MySQL database

9600
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import java.sql.*; import java.util.Collections; @Controller public class UsersController { @Autowired private JdbcTemplate jdbcTemplate; // POST http://localhost:8080/api/user/create // echo '{"name":"john","email":"john@email.com"}' | curl -X POST -H "Content-Type: application/json" -d @- http://localhost:8080/api/user/create // @PostMapping( value = "/api/user/create", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE ) @ResponseBody public Object createUser(@RequestBody UserEntity userEntity) throws SQLException { String query = "INSERT INTO `users`\n" + "\t(`name`, `email`)\n" + "VALUES\n" + "\t(?, ?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); PreparedStatementCreator statementCreator = (Connection connection) -> { PreparedStatement preparedStatement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, userEntity.getName()); preparedStatement.setString(2, userEntity.getEmail()); return preparedStatement; }; int updatesCount = this.jdbcTemplate.update(statementCreator, keyHolder); if (updatesCount == 1) { Number generatedKey = keyHolder.getKey(); if (generatedKey == null) { throw new SQLException("Getting user id error."); } long userId = generatedKey.longValue(); // inserted user id return Collections.singletonMap("userId", userId); } throw new SQLException("Expected one row insert."); // should never happen } }