๐Ÿง‘โ€๐Ÿ’ป [Spring Boot] ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ค๊ธฐ

J_m2nยท2024๋…„ 2์›” 16์ผ
0



MySQL์— ์žˆ๋Š” ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ค๊ธฐ

> ์ „์ฒด ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ค๊ธฐ

  1. Repository์— ๋ฐ”๋กœ ์ ‘๊ทผํ•˜๊ธฐ
@Autowired
private WritingRepo writingRepo;

@GetMapping("/")
    public ModelAndView every(Model model){
        ModelAndView mav = new ModelAndView();

        //1. ๋ชจ๋“  ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ค๊ธฐ
        List<Writing> writingEntityList = writingRepo.findAll();

        //2. ๋ชจ๋ธ์— ๋ฐ์ดํ„ฐ ๋“ฑ๋กํ•˜๊ธฐ
        model.addAttribute("writingList",writingEntityList);

        mav.setViewName("main");
        //3. ๋ทฐ ํŽ˜์ด์ง€ ์„ค์ •ํ•˜๊ธฐ
        return mav;
    }

  1. Service๋ฅผ ํ†ตํ•ด ์ ‘๊ทผํ•˜๊ธฐ
@Autowired
private WritingService wrService;

@GetMapping("/")
    public ModelAndView every(Model model){
        ModelAndView mav = new ModelAndView();

        //1. ๋ชจ๋“  ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ค๊ธฐ
        List<Writing> writingEntityList = wrService.index();

        //2. ๋ชจ๋ธ์— ๋ฐ์ดํ„ฐ ๋“ฑ๋กํ•˜๊ธฐ
        model.addAttribute("writingList",writingEntityList);

        mav.setViewName("main");
        //3. ๋ทฐ ํŽ˜์ด์ง€ ์„ค์ •ํ•˜๊ธฐ
        return mav;
    }


ํ…Œ์ด๋ธ”์˜ PK๋กœ ํ•œ ๊ฐ€์ง€ ๋ฐ์ดํ„ฐ์— ์ ‘๊ทผํ•  ๋•Œ

  1. Repository๋กœ ๋ฐ”๋กœ ์ ‘๊ทผํ•˜๊ธฐ
@Autowired
private WritingRepo writingRepo;

@GetMapping("/detail")
    public ModelAndView detail(@RequestParam("no") long no){
        ModelAndView mav = new ModelAndView();
        
        Writing data = writingRepo.findById(no).orElse(null);
        mav.addObject("data", data);

        mav.setViewName("content");
        return mav;
    }

โ—๏ธโ—๏ธโ—๏ธ ์ฒ˜์Œ์—๋Š” Optional<T> ํ˜•ํƒœ๋กœ ๋ฐ›์•„์™”์—ˆ๋Š”๋ฐ ์ด๊ฑด ์ฒ˜์Œ๋ณด๋Š” ํ˜•ํƒœ๋ผ ๋ญ”์ง€ ๋ชจ๋ฅด๊ฒ ์–ด์„œ ์—๋Ÿฌ๊ฐ€ ๊ณ„์† ๋ฐœ์ƒํ–ˆ์Œ. ๊ทธ๋ž˜์„œ ๊ทธ๋ƒฅ ๋ฐ”๋กœ Writing Entity ๊ฐ์ฒด๋กœ ๋ฐ”๋กœ ๋ฐ›์•„์™”์Œ.


2. Service๋กœ ์ ‘๊ทผํ•˜๊ธฐ
@Autowired
private WritingService wrService;

@GetMapping("/detail")
  public ModelAndView detail(@RequestParam("no") long no){
      ModelAndView mav = new ModelAndView();
      
      Writing data = writingRepo.findById(no).orElse(null);
      mav.addObject("data", data);

      mav.setViewName("content");
      return mav;
  }

โ—๏ธโ—๏ธโ—๏ธ ๊ทธ๋ฆฌ๊ณ  JSP์—์„œ๋Š” ์–ด์ฐจํ”ผ ๋‹จ์ผ ๋ฐ์ดํ„ฐ์ด๊ธฐ ๋•Œ๋ฌธ์— ${data.title} ์ด๋Ÿฐ์‹์œผ๋กœ ์“ฐ๋ฉด ๋จ!!

profile
์ฝ”๋”ฉ ์ดˆ์งœ์ž…๋‹ˆ๋‹ค

0๊ฐœ์˜ ๋Œ“๊ธ€