この記事はこれの続きです
Repositoryクラス
変更無しです。
Serviceクラス
Repositoryクラスの save()
で1レコード分、 saveAll()
で複数レコード分。
UnkoService
package com.example.demo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class UnkoService {
@Autowired
UnkoRepository unkoRepository;
public List<Unko> findAll() {
return unkoRepository.findAll();
}
public void insertOne(Unko unko) {
unkoRepository.save(unko);
}
public void insertAll(List<Unko> list) {
unkoRepository.saveAll(list);
}
}
Controllerクラス
DemoController.java
package com.example.demo;
import java.util.ArrayList;
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;
@Controller
public class DemoController {
@Autowired
UnkoService unko_service;
@GetMapping("/")
public String getIndex(Model model) {
//AUTOINCREMENTが設定されているrecord_idは値をセットしなくてOK。
//1レコードだけインサート。
Unko unko_ = new Unko();
unko_.setTest_val("にゃあ");
unko_service.insertOne(unko_);
//複数レコードインサート。
List<Unko> insert_list_ = new ArrayList<Unko>();
Unko u_1_ = new Unko();
u_1_.setTest_val("ほげえ");
insert_list_.add(u_1_);
Unko u_2_ = new Unko();
u_2_.setTest_val("ふがあ");
insert_list_.add(u_2_);
unko_service.insertAll(insert_list_);
//全レコード取得してThymeleafの変数にセット。
model.addAttribute("unko_list", unko_service.findAll());
return "/index";
}
}
実行結果
インサート先のテーブルはあらかじめ全レコード削除した状態で実行しました。
この記事の続き
バージョン
Microsoft Windows [Version 10.0.19045.4170]
Spring Boot v3.1.9