serviceは、selectと変更なし
SyainRepository.java
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository public class SyainRepository { private final JdbcTemplate jdbcTemplate; @Autowired public SyainRepository(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void insertSyain(Syain syain) { jdbcTemplate.update("INSERT INTO syain(id,name,romaji) Values(?,?,?)", syain.getId(),syain.getName(),syain.getRomaji()); } }
MainController.java
package com.example.demo; import java.time.LocalDateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/test1") public class MainController { @Autowired private SyainRepository syainRepository; @GetMapping public String index(Model model) { Syain syain = new Syain(); syain.setId(4); syain.setName("武田"); syain.setRomaji("takeda"); syainRepository.insertSyain(syain); return "test1/index"; } }
$ psql -U root test
psql (13.1)
Type “help” for help.
test=> select * from syain;
id | name | romaji
—-+——+——–
1 | 鈴木 | suzuki
2 | 田中 | tanaka
3 | 佐藤 | sato
(3 rows)
index.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8" /> <title>Check</title> </head> <body> ok </body> </html>
http://localhost:8080/test1
test=> select * from syain;
id | name | romaji
—-+——+——–
1 | 鈴木 | suzuki
2 | 田中 | tanaka
3 | 佐藤 | sato
4 | 武田 | takeda
(4 rows)
なるほど、CRUDはJDBCを使うのね、完全に理解した!