centos8でpostgresをインストールする

# systemctl restart firewalld
# sudo firewall-cmd –permanent –add-port=8756/tcp
success
# systemctl restart firewalld
# ls
practice-0.0.1-SNAPSHOT.jar
# java -jar practice-0.0.1-SNAPSHOT.jar

-> postgresが入ってないのでエラーになる

# yum module list postgresql
Failed to set locale, defaulting to C.UTF-8
Last metadata expiration check: 0:27:06 ago on Sat Feb 20 12:56:42 2021.
CentOS Linux 8 – AppStream
Name Stream Profiles Summary
postgresql 9.6 client, server [d] PostgreSQL server and client module
postgresql 10 [d] client, server [d] PostgreSQL server and client module
postgresql 12 client, server [d] PostgreSQL server and client module
# yum install -y @postgresql:12/server
# /usr/bin/postgresql-setup –initdb
# systemctl start postgresql
# systemctl enable postgresql
# psql –version
psql (PostgreSQL) 12.5

なんや
vi /var/lib/pgsql/data/pg_hba.conf
psql -h localhost -U postgres
alter role root with superuser login password ”;
ALTER USER root WITH PASSWORD ‘password’;

# psql -U root test
Password for user root:
psql (12.5)
Type “help” for help.

test=#

なんか色々触ってたらできたな

[CentOS8] jdk-11をインストールする

# sudo yum update
# cat /etc/redhat-release
CentOS Linux release 8.3.2011
# java -version
openjdk version “1.8.0_275”
# yum remove java-1.8.0-openjdk
# yum install -y java-11-openjdk
# java -version
openjdk version “1.8.0_275”

あれあれ???
-> デフォルトでOpenJDK8がインストールされている為、alternativesコマンドで11に切り替える必要がある。

# alternatives –config java

There are 2 programs which provide ‘java’.

Selection Command
———————————————–
*+ 1 java-1.8.0-openjdk.x86_64 (/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.275.b01-1.el8_3.x86_64/jre/bin/java)
2 java-11-openjdk.x86_64 (/usr/lib/jvm/java-11-openjdk-11.0.9.11-3.el8_3.x86_64/bin/java)

Enter to keep the current selection[+], or type selection number: 2
# java -version
openjdk version “11.0.9.1” 2020-11-04 LTS
OpenJDK Runtime Environment 18.9 (build 11.0.9.1+1-LTS)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.9.1+1-LTS, mixed mode, sharing)

なるほど

[SpringBoot2.4.2] jdbcTemplateの削除を実装する

index.html

<a th:href="'/test1/delete/' + ${list.id}"><button type="button" class="btn btn-danger">削除</button></a>

delete_complete.html

<h1>社員情報削除 完了</h1>
<div class="col-md-8">
<p>社員の削除が完了しました。</p>
<table class="table">
	<tr><td>名前</td><td th:text="${name}"></td></tr>
	<tr><td>所属</td><td th:text="${department}"></td></tr>
</table>
<button type="button" class="btn btn-primary" onclick="location.href='/test1/index'">一覧に戻る</button>
</div>

UserRepository.java

	public Users delete(Long id) throws DataAccessException {
        String sql1 = ""
            + "SELECT * FROM users WHERE id = ?";
        Map<String, Object> users = jdbcTemplate.queryForMap(sql1, id);
        Users user = new Users();
        user.setName((String)users.get("name"));
		user.setDepartment((String)users.get("department"));
		
		String sql2 = "DELETE FROM users WHERE id = ?";
	    jdbcTemplate.update(sql2, id);
        return user;
    }

MainController.java

	@GetMapping("delete/{userId}")
	public String deleteUser(@PathVariable("userId") long userId, Model model) {
		Users user = usersRepository.delete(userId);
        model.addAttribute("name", user.getName());
        model.addAttribute("department", user.getDepartment());
        return "test1/delete_complete";
	}

一度理解するとあとは早いな
とりあえずCRUD完
authに行きたいが、まずこれでVPSにデプロイしてみたい。

[SpringBoot2.4.2] 編集画面から編集完了画面を作る

画面遷移としては、編集->編集確認->編集完了

edit_confirm.html

<form class=""  method="get" action="/test1/editcomplete">
<input type="hidden" name="id" th:value="${id}">
<input type="hidden" name="name" th:value="${name}">
<input type="hidden" name="department" th:value="${department}">
<table class="table">
	<tr><td>名前</td><td th:text="${name}"></td></tr>
	<tr><td>所属</td><td th:text="${department}"></td></tr>
</table>
<button type="button" class="btn btn-primary" onclick="location.href='/test1/index'">戻る</button>
<button type="submit" class="btn btn-primary">編集完了</button>
</form>

MainController.java

@GetMapping("editconfirm")
	public String editconfirm(
			@RequestParam(name = "id") Integer id,
			@RequestParam(name = "name") String name,
			@RequestParam(name = "department") String department,
			Model model) {
			model.addAttribute("id", id);
			model.addAttribute("name", name);
			model.addAttribute("department", department);
			return "test1/edit_confirm";
	}

ここまでは何も考えずにいける
updateする為にnameとdepartment以外にidも加える

UsersRepository.java
L エンティティの値をupdate

public Users update(Users users) throws DataAccessException {
        // SQL文を作成
        String sql = ""
            + "UPDATE users SET name = ?, department = ?"
            + " WHERE"  + " id = ?";
        jdbcTemplate.update(sql, users.getName(),users.getDepartment(),users.getId());
        return users;
    }

MainController.java

@GetMapping("editcomplete")
	public String editcomplete(
			@RequestParam(name = "id") Integer id,
			@RequestParam(name = "name") String name,
			@RequestParam(name = "department") String department,
			Model model) {
		    Users users = new Users();
		    users.setId(id);
		    users.setName(name);
		    users.setDepartment(department);
		    usersRepository.update(users);
		    
			model.addAttribute("name", name);
			model.addAttribute("department", department);
			return "test1/edit_complete";
	}

updateされました。

よしゃああああああああああああああああああああああああ
SpringBootもCRUまできた。残りはDやな。

[SpringBoot2.4.2] URLのパスを取得してjdbcTemplateでedit画面を作成する

まずtemplates に edit.html を作ります。

<div class="form-group">
	    <label class="control-label col-md-2">名前</label>
	    <div class="col-md-4">
	        <input type="text" class="form-control" name="name" th:value="${name}">
	    </div>
	</div>
	<div class="form-group">
        <label class="control-label col-md-2">所属部署</label>
        <div class="col-md-4">
            <input type="text" class="form-control" name="department" th:value="${department}">
        </div>
    </div>

続いて、indexからeditへのリンク。これは、/edit/${userId}とします。

<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>

UsersRepository.java
L jdbcTemplate.queryForMapで取得する

public Users selectOne(Long id) throws DataAccessException {
        // SQL文を作成
        String sql = ""
            + "SELECT"
                + " *"
            + " FROM"
                + " users"
            + " WHERE"
                + " id = ?";
        Map<String, Object> users = jdbcTemplate.queryForMap(sql, id);

        // Userオブジェクトに格納する。
        Users user = new Users();
        user.setName((String)users.get("name"));
		user.setDepartment((String)users.get("department"));
        return user;
    }

MainController.java

	@GetMapping("edit/{userId}")
	public String editForm(@PathVariable("userId") long userId, Model model) {
		Users user = usersRepository.selectOne(userId);
        model.addAttribute("name", user.getName());
        model.addAttribute("department", user.getDepartment());
        return "test1/edit";
	}

まじかよ、これ作るの3時間半くらいかかったんだけど。。。

[Java11.0.2] listとは

listとは要素が順位づけられたコレクションのこと
Javaではlistを扱う用にリストインターフェースが定義される
配列の場合、要素数を指定するが、listは要素数を指定しない

import java.util.ArrayList;
import java.util.List;

public class Main {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(1);
		list.add(2);
		for(Integer l : list){
			System.out.println(l);
		}
	}
}

$ java test.java
1
2

import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

public class Main {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(4);
		list.add(5);
		list.add(1);
		list.add(2);
		for(Integer l : list){
			System.out.println(l);
		}

		Collections.sort(list);

		for(Integer l : list){
			System.out.println(l);
		}
	}
}

collectionsでソートもできる
なるほど、ListとMapの違いはわかった。

[Java11.0.2] mapとは

mapとは「キー」と「値」をペアにして複数データを格納できるもの
mapインスタンスを使うには、HashMapクラスを使う

Map<key型, value型> object = new HashMap<>();
import java.util.HashMap;
import java.util.Map;

public class Main {
	public static void main(String[] args) throws Exception {
		Map<Integer, String> map = new HashMap<>();

		map.put(1, "tanaka");
		map.put(3, "suzuki");
		map.put(5, "takahashi");

		System.out.println(map.get(1));
		System.out.println(map.get(3));
		System.out.println(map.get(5));
	}
}

$ java -version
openjdk version “11.0.2” 2019-01-15 LTS
$ java test.java
tanaka
suzuki
takahashi

keySet()でkeyの値を取り出せる

		for(Integer key: map.keySet()){
			System.out.println(key);
		}

なるほどー

[SpringBoot2.4.2] postgresのデータをselect文で全件取得して表示する

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の使い方を理解する必要がある。

[SpringBoot2.4.2] thymeleafの入力データをpostgresにINSERTする

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>

application.properties

spring.jpa.database=POSTGRESQL
spring.datasource.url=jdbc:postgresql://localhost:5432/test
spring.datasource.username=root
spring.datasource.password=

### データ格納用のDBテーブル作成
$ psql -U root test
psql: error: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket “/tmp/.s.PGSQL.5432”?
ん?
$ postgres -D /usr/local/var/postgres
$ brew services restart postgresql
test=> \d
test=> CREATE TABLE users (
id SERIAL NOT NULL,
name varchar(255),
department varchar(255),
PRIMARY KEY(id)
);

### Repository
Users.java

package com.example.demo;

public class Users {
	private Integer id;
	private String name;
	private String department;

	public Integer getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	public String getDepartment() {
		return department;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setDepartment(String department) {
		this.department = department;
	}
}

UsersRepository.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 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());
	}
}

MainController.java

package com.example.demo;
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("input")
	public String input1() {
		return "test1/input";
	}
	
	@GetMapping("inputconfirm")
	public String output1(
			@RequestParam(name = "name") String name,
			@RequestParam(name = "department") String department,
			Model model) {
			model.addAttribute("name", name);
			model.addAttribute("department", department);
			return "test1/input_confirm";
	}
	
	@GetMapping("inputcomplete")
	public String output2(
			@RequestParam(name = "name") String name,
			@RequestParam(name = "department") String department,
			Model model) {
		    Users users = new Users();
		    users.setName(name);
		    users.setDepartment(department);
		    usersRepository.insertUsers(users);
		    
			model.addAttribute("name", name);
			model.addAttribute("department", department);
			return "test1/input_complete";
	}
	
}

view

postgres側
test=> select * from users;
id | name | department
—-+———-+————
1 | 山田太郎 | 営業部
(1 row)

test=> select * from users;
id | name | department
—-+————+————
1 | 山田太郎 | 営業部
2 | 佐藤 祐一 | 経理部
(2 rows)

入力できてるーーーーーーーーーーーーーーーーー
ぎゃあああああああああああああああああああああああああああああ
😇😇😇😇😇😇😇😇😇😇😇😇😇

なんとなくServiceとRepositoryとControllerとthymeleafの関係性がわかってきたああああああああああ

[SpringBoot2.4.2] 登録確認画面を作る

src/main/resources/templates/test1/input_confirm.html
 L thymeleafでinput typeのvalueを取得して表示する

<form class=""  method="get" action="inputcomplete">
<input type="hidden" name="name" th:value="${name}">
<input type="hidden" name="department" th:value="${department}">
<table class="table">
	<tr><td>名前</td><td th:text="${name}">狩野 良平</td></tr>
	<tr><td>所属</td><td th:text="${department}">営業部</td></tr>
</table>
<button type="button" class="btn btn-primary" onclick="location.href='/test1/input'">戻る</button>
<button type="submit" class="btn btn-primary">登録完了</button>
</form>

MainController.java
 L completeもconfirmと基本は同じ、RequestParamで取得する

	@GetMapping("inputcomplete")
	public String output2(
			@RequestParam(name = "name") String name,
			@RequestParam(name = "department") String department,
			Model model) {
			model.addAttribute("name", name);
			model.addAttribute("department", department);
			return "test1/input_complete";
	}

src/main/resources/templates/test1/input_complete.html

	<link th:href="@{/css/style.css}" rel="stylesheet" type="text/css">

// 省略

<h1>社員登録 完了</h1>
<div class="col-md-8">
<p>社員の登録が完了しました。</p>
<table class="table">
	<tr><td>名前</td><td th:text="${name}">狩野 良平</td></tr>
	<tr><td>所属</td><td th:text="${department}">営業部</td></tr>
</table>
<button type="button" class="btn btn-primary" onclick="location.href='/index'">一覧に戻る</button>
</div>

GetではなくPostにしたいが、Getなら凄く簡単だということはわかった。
ファイルのルーティングはControllerでやるのね。

で、この入力データをINSERTしたい。