티스토리 뷰

- myBatis 설정

<dependency>
    <groupId>org.mariadb.jdbc</groupId>
    <artifactId>mariadb-java-client</artifactId>
    <version>3.0.8</version>
</dependency>


<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

- application.properties

mybatis.mapper-locations=classpath:mappers/**/*.xml 

spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://localhost:12602
spring.datasource.username=study
spring.datasource.password=test1234

참고

https://winhyun.tistory.com/25

 

[String Boot] MyBatis

MyBatis 필요한 DB 관련 메서드는 인터페이스에 정의하고, 그 인터페이스 및 이가 포함하는 메서드 등을 외부 XML과 연결하여 쿼리를 자바 코드와 분리하여 관리하기 위해 사용한다. 엔티티(Entity)

winhyun.tistory.com


- DB

CREATE TABLE `study`.`memos`
(
    `index` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(10) NOT NULL,
    `text` VARCHAR(100) NOT NULL,
    CONSTRAINT PRIMARY KEY (`index`)
);

 기본 DB을 세팅한다.  DB를 만들었다면 무엇을 해야할까? 바로~ 엔티티 만들러 가야GG DB와 엔티티는 1:1 매핑관계이기 때문!


- MemoEntity.java 

package dev.shlee.study_web.entities.study;

import java.util.Objects;

public class MemoEntity {
    private int index; 
    private String name;
    private String text;


    public int getIndex() 
        return index; 
    }

    public void setIndex(int index) { 
        this.index = index; 
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    @Override
    public boolean equals(Object o) { 
        if (this == o) return true; 
        if (o == null || getClass() != o.getClass()) return false; 
        MemoEntity that = (MemoEntity) o; 
        return index == that.index;
    }

    @Override
    public int hashCode() {
        return Objects.hash(index);
    }
}

- MemoMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dev.shlee.study_web.mappers.IMemoMapper">
    <insert id="insertMemo"
            useGeneratedKeys="true"
            keyColumn="index"
            keyProperty="index"
            parameterType="dev.shlee.study_web.entities.study.MemoEntity">
        INSERT INTO `study`.`memos` (`name`, `text`)
        VALUES (#{name},#{text})
    </insert>

    <select id="selectMemos"
        resultType="dev.shlee.study_web.entities.study.MemoEntity">
    SELECT `index` AS `index`,
           `name` AS `name`,
           `text` AS `text`
    FROM `study`.`memos`
    ORDER BY `index` DESC
    </select>


    <delete id="deleteMemo"
    parameterType="dev.shlee.study_web.entities.study.MemoEntity">
        DELETE
        FROM `study`.`memos`
        WHERE `index` = #{index}
        LIMIT 1
    </delete>

</mapper>

- xml에 insert, select, delete 만들어 준다! 왜 why? 메모장에는 select, insert, delete가 다 필요하니깐!


- IMemoMapper

package dev.shlee.study_web.mappers;

import dev.shlee.study_web.entities.study.MemoEntity;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface IMemoMapper {

    int insertMemo(MemoEntity memo);

    MemoEntity[] selectMemos();

    int deleteMemo(MemoEntity memo);
}

- IMemoMapper interface를 만들어준다. insertMemo, selectMemos, deleteMemo 는 무엇일까? xml에서 만든 각각의 id이다.  풀어서 해석해보면 int형 insertMemo에 매개변수로(MemoEntity memo)를 만들어준다. 근데  select는 왜 배열로 받았을까? 값을 한꺼번에 받아와야하기 때문이다.


- MemoService.java

package dev.shlee.study_web.services;

import dev.shlee.study_web.entities.study.MemoEntity;
import dev.shlee.study_web.mappers.IMemoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;


@Service(value = "dev.shlee.study_web.services.MemoService")
public class MemoService {
    private final IMemoMapper memoMapper;

    @Autowired
    public MemoService(IMemoMapper memoMapper) {
        this.memoMapper = memoMapper;
    }

    public void addMemo(MemoEntity memo) {
        this.memoMapper.insertMemo(memo);
    }

    public MemoEntity[] getMemos() {
        return this.memoMapper.selectMemos();
    }

    public void deleteMemo(MemoEntity memo) {
        this.memoMapper.deleteMemo(memo);
    }
}

- MemController

package dev.shlee.study_web.controllers;

import dev.shlee.study_web.entities.study.MemoEntity;
import dev.shlee.study_web.services.MemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.sql.SQLException;

@Controller(value = "dev.shlee.study_web.controllers.MemoController")
@RequestMapping(value = "/memo")
public class MemoController {
    private final MemoService memoService;

    @Autowired
    public MemoController(MemoService memoService) { // MemoContorller를 객체화를 하기 위해 생성자를 만든다
        this.memoService = memoService;
    }


    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView getIndex() {
        MemoEntity[] memos = this.memoService.getMemos();
        ModelAndView modelAndView = new ModelAndView("memo/index");
        modelAndView.addObject("memos", memos);
        return modelAndView;
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public ModelAndView postIndex(MemoEntity memo) throws ClassNotFoundException, SQLException {
        this.memoService.addMemo(memo);
//        MemoEntity[] memos = this.memoService.postMemos();
//        ModelAndView modelAndView = new ModelAndView("memo/index");
//        modelAndView.addObject("memos",this.memoService.getMemos());
//        System.out.println(memo.getIndex()); // 0이 찍힘
        System.out.printf("이름 : %s\n", memo.getName());
        System.out.printf("나이 : %s\n", memo.getText());
        System.out.println(memo.getIndex());

        return this.getIndex(); // 위에 주석 표시된 코드를 줄인 것.
    }


    //강사님 버전
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public ModelAndView getDelete(MemoEntity memo) throws InterruptedException {
        this.memoService.deleteMemo(memo);
//        System.out.println(memo.getIndex()); // 확인해보기 위한..
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:./");

//        Thread.sleep(2500); //2.5초 delete?index=4 에서 대기

        return modelAndView;
    }
}


// -로직
//        Class.forName("org.mariadb.jdbc.Driver");
//        Connection connection = DriverManager.getConnection(
//                "jdbc:mariadb://localhost:12602",
//                "study",
//                "test1234");
//        try (connection) {
//            try (PreparedStatement preparedStatement = connection.prepareStatement("" +
//                    "INSERT INTO `study`.`memos`  (`name`,`text`) " +
//                    "VALUES (?, ?)")) {
//                preparedStatement.setString(1, memo.getName());
//                preparedStatement.setString(2, memo.getText());
//                preparedStatement.executeUpdate();
//
//            }
//        }
// -로직 여기까지


 

'웹 개발 > SpringBoot' 카테고리의 다른 글

[String Boot] JSON  (0) 2022.11.07
[String Boot] 메모장 구현 복습 Part 1  (2) 2022.11.06
[String Boot] ANNOTATION 공부  (0) 2022.11.04
[Spring Boot] 프로젝트 구조  (0) 2022.11.03
[Spring Boot] MVC 패턴  (2) 2022.11.03
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2026/04   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
글 보관함