この記事はこれの続きです
Repositoryクラス
変更無しです。
Serviceクラス
Repositoryクラスの save()
で1レコード分、 saveAll()
で複数件。
UnkoService.java
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 upsertOne(Unko unko) {
unkoRepository.save(unko);
}
public void upsertAll(List<Unko> list) {
unkoRepository.saveAll(list);
}
public void deleteOne(Unko unko) {
unkoRepository.delete(unko);
}
public void deleteAll() {
unkoRepository.deleteAll();
}
}
Controllerクラス
DemoController.java
package com.example.demo;
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) {
//既存レコードはアップデート。
Unko unko_1_ = new Unko();
unko_1_.setRecord_id(1);
unko_1_.setTest_val("レコード1変更後の値");
unko_service.upsertOne(unko_1_);
//存在しなければインサート。
Unko unko_2_ = new Unko();
unko_2_.setRecord_id(2);
unko_2_.setTest_val("レコード2の新規挿入値");
unko_service.upsertOne(unko_2_);
return "/index";
}
}
実行結果
インサート分のrecord_idが『9』なことに注目。
- record_id = 2のレコードは無いのでインサート。
- record_idはAUTOINCREMENTでインサート前は『次の値は9』の状態になっていた。
- 『record_id = 2』ではなく『record_id = 9』でレコードが挿入された。
この記事の続き
バージョン
Microsoft Windows [Version 10.0.19045.4170]
Spring Boot v3.1.10