[Spring Boot] TodoList(1)-Mybatis 연동 및 회원가입 기능 구현

전수·2022년 12월 3일
0

Spring

목록 보기
4/13

Spring Boot 설정

Intellj
✔ laguage : java
✔ build type : gradle-groovy
✔ JDK : 1.8
✔ JAVA : 8
✔ Packaging : JAR
✔ Spring Boot : 2.7.6
✔ Dependency : Web(Spring Web)

😀Spring MVC에 비해 Spring Boot 기본 설정이 훨씬 편하다

🙋‍♀️프로젝트는 회원가입, 로그인을 구현하고 가입된 회원은 TodoList 페이지에 접근하여 각자의 TodoList를 작성하는 내용이다.


DB Table 생성 및MyBatis 연동

우선 DB는 Maria DB를 사용하였다. 처음 사용해보지만 mysql문법을 동일하게 사용하기 때문에 큰 문제없이 진행할 수 있었다.

📌Member Table 생성

create table member (
	firstName varchar(30) not null,
	phone varchar(30) not null,
	email varchar(30) not null,
	password varchar(30) not null,
	gender varchar(10) not null,
	primary KEY(email)
	);

회원가입 시 필요한 정보로 이름, 전화번호, 이메일, 비밀번호, 성별이 있다. 그 중 이메일을 PRIMARY KEY로 설정하였다.

📌Dependency 추가

build.gradlemybatismariaDB dependency를 추가해야 한다.

implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.2'
implementation 'org.mariadb.jdbc:mariadb-java-client:3.0.6'

📌application-properties 설정

maria DBmybatis-mapper을 연동하기 위해 application-properties에 설정이 필요하다.

spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://127.0.0.1:3307
spring.datasource.username=xxxx
spring.datasource.password=xxxx

mybatis.mapper-locations= mybatis-mapper/**/*.xml

url
localhost 주소에 DB 생성 시 설정한 DB port 번호를 입력해야 한다. default는 3306이지만 나의 경우 mysql이 먼저 설치되어 있었기 때문에 port 충돌이 발생하여 3307로 설정하였다.

username
maria DB 생성 시 설정한 ID 값을 작성한다.대부분 root가 default 값으로 설정되었을 것이다

password
maria DB 생성 시 설정한 password 값을 작성한다.

mybatis.mapper-locations
mapper.xml의 위치를 작성한다. 나의 경우 resources - mybatis-mapper - mapper.xml 구조로 작성되었다.

📌Mapper 생성 및 MapperScan 등록하기

프로젝트에 mapper.java 파일을 생성한다.해당 파일은 Interface로 생성하며 mapper.xml 파일과 같이 개발자가 신경쓰고 관리해야 하는 파일이다.
✔ 파일 생성 후 @Mapper annotation을 붙여준다.

@Mapper
public interface TodoListMapper {}

✔ Mapper을 생성했다면 application.java에 @MapperScan을 등록한다.

@SpringBootApplication
@MapperScan(value = {"com.example.todolist.mapper"})
public class TodoListApplication {

    public static void main(String[] args) {
        SpringApplication.run(TodoListApplication.class, args);
    }

}

📌DTO Model 생성하기

회원가입 시 이름, 전화번호, 이메일, 비밀번호, 성별의 정보를 받게 되는데 해당 정보를 member 객체에 담아 전달하기 위해 DTO 모델을 생성하였다.

 <div class="box">
      <label for="firstName" class="fl fontLabel"> 이름: </label>
      <div class="new iconBox">
        <i class="fa fa-user" aria-hidden="true"></i>
      </div>
      <div class="fr">
        <input type="text" name="name" placeholder="이름.."
               class="textBox" autofocus="on" required>
      </div>
      <div class="clr"></div>
    </div>
    <!--name-->

    <!---Phone No.------>
    <div class="box">
      <label for="phone" class="fl fontLabel"> 핸드폰번호: </label>
      <div class="fl iconBox"><i class="fa fa-phone-square" aria-hidden="true"></i></div>
      <div class="fr">
        <input type="text" required name="phone" maxlength="10" placeholder="핸드폰번호.." class="textBox">
      </div>
      <div class="clr"></div>
    </div>
    <!---Phone No.---->

    <!---Email ID---->
    <div class="box">
      <label for="email" class="fl fontLabel"> 이메일: </label>
      <div class="fl iconBox"><i class="fa fa-envelope" aria-hidden="true"></i></div>
      <div class="fr">
        <input type="email" required name="email" placeholder="이메일.." class="textBox">
      </div>
      <div class="clr"></div>
    </div>
    <!--Email ID----->

    <!---Password------>
    <div class="box">
      <label for="password" class="fl fontLabel"> 비밀번호 </label>
      <div class="fl iconBox"><i class="fa fa-key" aria-hidden="true"></i></div>
      <div class="fr">
        <input type="Password" required name="password" placeholder="비밀번호.." class="textBox">
      </div>
      <div class="clr"></div>
    </div>
    <!---Password---->

    <!---Gender----->
    <div class="box radio">
      <label for="gender" class="fl fontLabel"> 성별: </label>
      <input type="radio" name="gender" value="Male" required> 남성 &nbsp; &nbsp; &nbsp; &nbsp;
      <input type="radio" name="gender" value="Female" required> 여성
    </div>
    <!---Gender--->

❗위와 같이 name, phone, email, password, gender 이름으로 값을 받기 때문에 DTO 파일도 동일한 형식으로 생성해야 한다.

public class MemberDTO {
    private String name;
    private String phone;
    private String email;
    private String password;
    private String gender;

    public MemberDTO(String name, String phone, String email, String password, String gender) {
        this.name = name;
        this.phone = phone;
        this.email = email;
        this.password = password;
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}

📌mapper.xml 작성하기

mybatis-mapper 하단에 mapper.xml를 생성하고 mapper namespace를 mapper.java의 위치로 설정한다.

<?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="com.example.todolist.mapper.TodoListMapper">

📌insert query

<insert id="insertMember" parameterType="com.example.todolist.dto.MemberDTO">
        INSERT INTO member VALUES (#{name},#{phone},#{email},#{password},#{gender})
</insert>

회원가입을 구현하기 위해 insertMember로 설정하였고 parameterTypeMemberDTO로 받게 된다. 이때 MemberDTO 파일의 위치로 명시해야 객체로 받을 수 있다.

📌MemberInsert 구현하기

DB에 접근하기 위한 과정을 완성했고 Controller에서 해당 기능을 수행할 수 있도록 연결하는 작업이 필요하다. 어떠한 기능을 구현하든 동일한 순서{Controller - Service - Repository - Mapper}로 작성되고 진행될 것이다.
📌Mapper.java

public int insertMember(MemberDTO memberDTO);

Insert문을 수행하면 수행된 쿼리의 개수를 반환하게 된다. 따라서 int를 반환하는 메서드를 작성하였다.
📌Repository

@Repository
public class MemberRepository {

    @Autowired
    TodoListMapper mapper;

    public int insertMember(MemberDTO memberDTO){
        return mapper.insertMember(memberDTO);
    }
}

Repository파일을 생성하여 @Repository를 등록하고 Mapper 변수를 생성하여 @Autowired 등록한다.
Mapper.java에 작성한 메서드를 동일하게 작성하면 된다.
📌 Service

@Service
public class MemberService {

    @Autowired
    MemberRepository mr;

    public int insertMember(MemberDTO memberDTO){
        return mr.insertMember(memberDTO);
    }
}

Repository와 동일한 형태로 작성하되 @Service를 등록하고 repository변수를 생성하여 @Autowired 등록한다.

📌 Controller

@Controller
public class MemberController {

    @Autowired
    MemberService ms;

    @PostMapping("/signup")
    public String signup(MemberDTO memberDTO){
        if(ms.insertMember(memberDTO) > 0){
            return "login";
        }
        return "index";
    }
}

회원가입이 성공하면 login창으로 이동하고 실패하면 index 화면으로 이동하도록 설정하였다.
따라서 해당 controller는 view를 반환하기 때문에 @Controller를 등록하였다.
Controller는 service 변수를 가지고 @Autowired 등록한다.
insertMember 메서드의 결과가 0보다 크다면 쿼리 수행을 성공한 것으로 알 수 있다.

📌예외 처리
현재 Email이 primary key로 등록되어 있다. 만약 이미 존재하는 Email 값으로 회원가입을 시도하면 sql 오류를 마주할 것이다. 이를 해결하기 위해 select문을 사용하여 전달받은 MemberDTO의 email 값이 동일한 값이 있는지 체크하는 checkMember 메서드를 추가적으로 구현하였다.

🏃‍♀️Github Link : [Spring Boot]TodoList

0개의 댓글

관련 채용 정보