UsersRepository.java
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 UsersRepository { private final JdbcTemplate jdbcTemplate; @Autowired public UsersRepository(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void insertUsers(Users users) { jdbcTemplate.update("INSERT INTO users(name,department) Values (?,?)", users.getName(), users.getDepartment()); } public List<Users> getAll(){ String sql = "select id, name, department from users"; List<Map<String, Object>>usersList = jdbcTemplate.queryForList(sql); List<Users> list = new ArrayList<>(); for(Map<String, Object> str1: usersList) { Users users = new Users(); users.setId((int)str1.get("id")); users.setName((String)str1.get("name")); users.setDepartment((String)str1.get("department")); list.add(users); } return list; } }
MainController.java
package com.example.demo; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/test1") public class MainController { @Autowired private UsersRepository usersRepository; @GetMapping("index") public String index(Model model) { List<Users> list = usersRepository.getAll(); model.addAttribute("UsersList", list); return "test1/index"; }
index.html
L 文字を接続する際は、”‘string’ + ${list}”とする
<h1>社員一覧</h1> <div class="col-md-8"> <table class="table"> <tr><th>ID</th><th>名前</th><th>所属部署</th><th>編集</th><th>削除</th></tr> <tr th:each="list: ${UsersList}"> <td th:text="${list.id}"></td><td th:text="${list.name}">狩野 良平</td><td th:text="${list.department}">営業部</td><td><a th:href="'/edit/' + ${list.id}"><button type="button" class="btn btn-secondary">編集</button></a></td><td><a th:href="'/delete/' + ${list.id}"><button type="button" class="btn btn-danger" onclick="location.href='/delete_complete.html'">削除</button></a></td> </tr> </table>
select allはわかった。
Javaの map, list, arrayListの使い方を理解する必要がある。