[Spring Boot2.4.2] SpringJDBCでselect

pom.xml

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<scope>runtime</scope>
		</dependency>

Syain.java

package com.example.demo;

public class Syain {
	
	private Integer id;
	private String name;
	private String romaji;
	
	public Integer getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	public String getRomaji() {
		return romaji;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setRomaji(String romaji) {
		this.romaji = romaji;
	}
}

SyainRepository.java
L mapとは、「キー」と「値」をペアにして複数のデータを格納できるもの
-> 連想配列みたいなものか。。

package com.example.demo;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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 List<Syain> getAll(){
		String sql = "select id, name, romaji from syain";
		List<Map<String, Object>>syainList = jdbcTemplate.queryForList(sql);
		List<Syain> list = new ArrayList<>();
		for(Map<String,Object> str1: syainList) {
			Syain syain = new Syain();
			syain.setId((int)str1.get("id"));
			syain.setName((String)str1.get("name"));
			syain.setRomaji((String)str1.get("romaji"));
			list.add(syain);
		}
		return list;
	}
}

MainController.java

package com.example.demo;
import java.util.List;
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.RequestMapping;

@Controller
@RequestMapping("/test1")
public class MainController {
	@Autowired
	private SyainRepository syainRepository;
	
	@GetMapping
	public String index(Model model) {
		List<Syain> list = syainRepository.getAll();
		model.addAttribute("SyainList", list);
		return "test1/index";
	}
}

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="utf-8" />
    <title>Check</title>
  </head>
  <body>
    <table>
    	<tr>
    		<th>id</th><th>name</th><th>romaji</th>
    	</tr>
    	<tr th:each="list : ${SyainList}">
    		<td th:text="${list.id}"></td>
    		<td th:text="${list.name}"></td>
    		<td th:text="${list.romaji}"></td>
    	</tr>
    </table>
  </body>
</html>

なんかもう殆どSpringBootでアプリ作れるような気がしてきた。