1024

이민규·2023년 10월 24일
1

Continuing from 1023

Boot 4 MyBatis_Service

Service

  • Spring Boot 4의 MyBatis 설정에 따르면, Sql문을 통한 DB의 데이터가 Controller-DB 직접 교환됨 (@Mapper에 등록된 클래스는 단순 매개자일뿐)
  • DB의 데이터를 처리할 Java Logic이 Controller에 전부 부담됨
  • 이러한 Controller의 부담을 분담할 객체가 Service
  • Service는 Controller와 DB 사이에서 데이터 처리를 위한 Java 로직을 담당하며 능동적 매개자로써 역할 (Framework의 DAO같은 역할)

Mapper

SQL

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="data.model.mapper.MarketMapperInter">
	//sql문
</mapper>
  • Sql문을 통해 데이터를 교환하는 Mapper

Interface

@Mapper
public interface MarketMapperInter {

	public int getTotalCount(); //메서드명이 id역할..id가 똑같아야함
	public List<MarketDto> getAllSangs();
	//메서드
}
  • @Mapper 어노테이션은 일반적으로 인터페이스를 등록
  • 그 이유는 MyBatis 설정에서 @Mapper로 등록된 객체는 단순히 데이터 전달만을 위한 중간 경로일 뿐이기 때문 (로직을 작성하지 않아도 되는 인터페이스가 적절)

Service

Interface

public interface MarketServiceInter {

	public int getTotalCount(); //메서드명이 id역할..id가 똑같아야함
	public List<MarketDto> getAllSangs();
	//메서드
}
  • @Mapper 등록하지 않은, Mapper 인터페이스와 동일한 객체를 생성
    • Controller에서 Mapper, Service 둘 모두를 호출하는 것은 비생산적이므로, Service를 사용하려면 모든 메서드를 Service에서 끌어 쓰는 것이 좋음
    • 어노테이션을 제외하면 Mapper 인터페이스와 완전히 동일하지만, 일반적으로 새로운 인터페이스 하나를 새로 만듦
    • 물론 인터페이스가 아닌 클래스로 생성할 수 있지만, overriding이 편리하므로 인터페이스로 생성

Class

@Service //dao개념,mapper보완기능
public class MarketService implements MarketServiceInter {
	
	@Autowired
	MarketMapperInter mapperInter;

	@Override
	public int getTotalCount() {
		return mapperInter.getTotalCount();
	}
	
	//메서드
}
  • Sql문을 통해 DB에서 입출력될 데이터를 처리 가능

Controller

@Controller
public class MarketController {

	//@Autowired
	//MarketMapperInter mapper;
	
	@Autowired
	MarketService service;

	@GetMapping("/market/delete")
	public String delete(@RequestParam int num,
			HttpSession session) {
		
		String fName=service.getData(num).getPhotoname();
		
		if(!fName.equals("")) {
			String path=session.getServletContext().getRealPath("/save");
			
			File file=new File(path+"\\"+fName);
			file.delete();
		}
		service.deleteMarket(num);
		
		return "redirect:list";
	}
}
  • Mapper에서 데이터를 직접 교환할 경우 Controller의 로직 부담이 커짐
  • Service에서 데이터를 일부 처리하여 Controller와 교환
  • Mapper 대신 Service 객체를 @Autowired 등록하여 사용
profile
초보개발자

0개의 댓글