pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>
jdbcTemplate使用
MessagesController.java
package com.example.demo; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("messages") public class MessagesController { @Autowired JdbcTemplate jdbcTemplate; @RequestMapping(method = RequestMethod.GET) public List<Message> getMessages(){ return jdbcTemplate.query("SELECT text FROM messages ORDER BY id", (rs, i)->{ Message m = new Message(); m.setText(rs.getString("text")); return m; }); } @RequestMapping(method = RequestMethod.POST) public Message postMessage(@RequestBody Message message) { jbdcTemplate.update("INSERT INTO messages(text) VALUES (?)", message.getText()); } }
spring bootはクラスパス直下にschema.sqlが存在すると、起動時にそのsqlを実行する
CREATE TABLE messages ( id INT PRIMARY KEY AUTO_INCREMENT, text VARCHAR(255) );
### PostgreSQLを使う方法
<dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency>
application.properties
string.datasource.username=root string.datasource.password=hoge spring.datasource.url=jdbc:postgresql://localhost:5432/spring
mysqlを使用する場合は、schema.sqlを用意するのが定石か