0
0

SpringBootでEntityを使ってMySQLのレコード削除(1件、全件)

Last updated at Posted at 2024-03-27

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

Repositoryクラス

変更無しです。

Serviceクラス

Repositoryクラスの delete() で1レコード分、 deleteAll() で全件。

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);
    }
    
    
    public void deleteOne(Unko unko) {
    	unkoRepository.delete(unko);
    }
    
    
    public void deleteAll() {
    	unkoRepository.deleteAll();
    }
    
}

Controllerクラス(1件削除)

DemoController
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_ = new Unko();
		//主キー以外のフィールドは値セット必要無し。
		unko_.setRecord_id(6);
		unko_service.deleteOne(unko_);
		
		
		return "/index";
		
		
	}
	
	
}

実行結果(1件分)

実行前。
image.png

実行後。
image.png

テーブルに存在しない主キーがEntityにセットされていた場合

例外にはならないです。
下記のようなSQLを流したのと同じ。

DELETE FROM neko.unko WHERE record_id = 6

Controllerクラス(全削除)

DemoController
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_service.deleteAll();
		
		
		return "/index";
		
		
	}
	
	
}

全レコード削除するだけなので実行結果は割愛。

この記事の続き

バージョン

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