0
0

SpringBootでEntityを使ってMySQLのレコード更新(アップサート)

Last updated at Posted at 2024-03-27

この記事はこれの続きです

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";
		
		
	}
	
	
}

実行結果

実行前。
image.png

実行後。
image.png

インサート分のrecord_idが『9』なことに注目。

  1. record_id = 2のレコードは無いのでインサート。
  2. record_idはAUTOINCREMENTでインサート前は『次の値は9』の状態になっていた。
  3. 『record_id = 2』ではなく『record_id = 9』でレコードが挿入された。

この記事の続き

バージョン

Microsoft Windows [Version 10.0.19045.4170]
Spring Boot v3.1.10

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0