Gyuseok
Dreaming_developer
Gyuseok
  • 분류 전체보기 (39)
    • Note (0)
    • TIL (8)
    • 일상 (1)
    • git & git hub (1)
    • Algorithm (14)
    • JAVA (5)
    • Spring & SpringBoot (10)
    • 기업연계 프로젝트 (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 관리자
  • 티스토리
  • 글작성

공지사항

인기 글

태그

  • MegabyteSchool
  • 패스트캠퍼스
  • java
  • 메가바이트스쿨
  • pattern
  • 내일배움카드
  • Builder
  • 개발자취업부트캠프
  • 국비지원교육
  • lombok

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Gyuseok

Dreaming_developer

Spring & SpringBoot

Spring Boot에서 MariaDB 와 MyBatis를 적용해보기

2022. 11. 30. 15:05

스프링과 스프링 부트를 배우다 보면 ORM과 DB는 뺴놓고 얘기할수 없다.
ORM은 Object Relational Mapping 즉 객체와 관계형 데이터 베이스를 매핑 해주는것을 말한다.

대표적으로 MyBatis, JDBC, JPA 등이 있다.

오늘은 MyBtis로 얘기하겠다.

 

 

Dependencies 추가

Gradle을 기준으로 build.gradle의 dependencies에서

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

해당 두줄의 dependencies를 추가해 줘야 한다.

내용에서 볼수있듯이 mybatis 와 mariadb에 관한 설정이다.

 

application.properties추가

resources 밑에 application.properties에 아래 내용을 추가해 준다.

spring.datasource.driver-class-name=org.mariadb.jdbc.Driver //DB드라이버 지정
spring.datasource.url=jdbc:mariadb://127.0.0.1:3306 //로컬 포트 지정
spring.datasource.username=xxxx //아이디
spring.datasource.password=xxxx //비밀번호

mybatis.mapper-locations= mybatis-mapper/**/*.xml  //xml파일 추가

 

 

mapper패키지와 mapper인터페이스 생성

mapper 패키지를 만들어 준다.

mapper 위치

위치는 사실 부트로 프로젝트 생성시 생기는 com.example./밑에 생성만 해주면 크게 상관 없다.

패키지를 생성했다면 mapper인터페이스를 생성해 주자.

package com.example.wilwebprac.mapper;

import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface exampleMapper {
}

어려울것 없이 인터페이스를 생성 후 @Mapper 어노테이션만 붙여주면 된다.

MapperScan 추가

다음은 SpringBootApplication에서 어노테이션 추가를 해줘야 한다.

스프링 부트로 프로젝트를 생성하면 기본적으로 있는 자바 파일이며 

com.example안에 들어있을것이고,

@SpringBootApplication

해당 어노테이션이 붙어있다.

@SpringBootApplication
@MapperScan(value={"com.example.wilwebprac.mapper"})

MapperScan어노테이션과 함께 전 단계에서 만든 mapper패키지의 위치를 위 예시와 같이 적어주면 된다.

mapper패키지의 위치를 잘못적게 되면 scan이 불가해 오류가 나게된다.

 

xml파일 추가

resources밑에 패키지를 생성한다.

이름은 크게 상관 없으며 안에 목적에 맞는 이름의 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="com.example.wilwebprac.mapper.userMapper">
    
    <insert id="signup" parameterType="HashMap">
        insert into user
        values((#{name}),(#{phone}),(#{email}),(#{password}),(#{gender}));
    </insert>

    <select id="login" parameterType="string" resultType="java.util.HashMap">
        select * from user where email =(#{email})
    </select>
    
</mapper>

 

해당 예시에는 insert 예시와 select 예시가 있다. 더 자세한 문법은 mapper문법을 찾아보는게 도움이 된다.

<mapper namespace="com.example.wilwebprac.mapper.userMapper">

해당 부분은 mapper패키지 안에서 현재 xml파일이 사용할 mapper인터페이스를 지정한다.

 

Repository 생성

package com.example.wilwebprac.repository;

import com.example.wilwebprac.mapper.userMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class userRepository {

    @Autowired
    userMapper usermapper;
    
}

Repository 어노테이션과 Autowired를 통해 Mapper인터페이스의 객체를 주입시켜준다.

 

Service 생성

package com.example.wilwebprac.user.service;

import com.example.wilwebprac.repository.userRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class userService {

    @Autowired
    userRepository userRepository;

}

마찬가지로 Service 어노테이션과 전단계에서 만든 Repository를 autowired를 통해 객체를 주입시켜준다.

 

Controller 생성

 

package com.example.wilwebprac.user.controller;

import com.example.wilwebprac.user.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class userController {

    @Autowired
    userService userService;
    
}

마찬가지로 Controller어노테이션과 전단계에서 만든 Service를 autowired를 통해 객체를 주입시켜준다.

 

이제 기본적인 셋팅은 끝났다.

 

기존 데이터 베이스에 유저 정보가 담겨있다는 전제 하에 로그인 하는 과정을 예시로 보여주겠다.

 

로그인 예시

가장 처음 할것은 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="com.example.wilwebprac.mapper.userMapper">

    <select id="login" parameterType="string" resultType="java.util.HashMap">
        select * from user where email =(#{email})
    </select>

</mapper>

첫째로 id값이다. id값은 mapper인터페이스에서 사용할 메서드와 이름을 일치 시켜야 한다.

parameterType은 들어올 값의 형태를 말한다. 해당 예시에서는 email을 String으로 parameter로 받고 결과를 HashMap으로 받겠다.

해당 테이블의 컬럼값

 

이제 mapper로 간다.

package com.example.wilwebprac.mapper;

import org.apache.ibatis.annotations.Mapper;

import java.util.HashMap;

@Mapper
public interface userMapper {
    public HashMap<String,String> login(String email);
}

xml의 resultType과 메서드의 리턴타입을 일치시키고, xml의 id와 인터페이스의 메서드명을 일치시킨다.

마지막으로 parameterType과 메서드의 변수타입을 일치시킨다.

 

이제 Repository로 간다.

package com.example.wilwebprac.repository;

import com.example.wilwebprac.mapper.userMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.HashMap;

@Repository
public class userRepository {

    @Autowired
    userMapper usermapper;
    
    public HashMap<String,String> login(String email){
        return usermapper.login(email);
    }
}

여기서부턴 메서드명을 맞추지는 않아도 되지만 가시성을 위해 메서드명을 유지하겠다.

마찬가지로 return타입과 input타입을 맞춰주면 된다.

return은 mapper의 메서드를 통해 얻은값을 리턴한다.

 

이제 Service로 가보자

package com.example.wilwebprac.user.service;

import com.example.wilwebprac.repository.userRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class userService {

    @Autowired
    userRepository userRepository;
    
    public String login(String email,String password){
        if (userRepository.login(email).get("password").equals(password)) {
            return userRepository.login(email).get("name");
        }else return null;
    }

}

Service에선 비즈니스적인 로직을 처리해야한다.

로그인 시도중 비밀번호 일치여부와 같은 로직은 서비스에서 처리하도록 한다.

Repository에서 넘어온 정보가 메서드 변수로 받은 email과 비밀번호와 일치하면 String으로 유저의 이름을 넘겨주고, 아닐경우 null을 통해 정보를 주지 않는다.

 

Controller로 가보자.

 

package com.example.wilwebprac.user.controller;

import com.example.wilwebprac.user.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Controller
public class userController {

    @Autowired
    HttpSession session;

    @Autowired
    userService userService;

    @PostMapping("login")
    public String login(@RequestParam HashMap<String,String> user){
        String name = userService.login(user.get("email"),user.get("password"));
        if(name!=null){
            session.setAttribute("SESSION_NAME",name);
            return "index";
    }
    return "login";
    }
    
}

PostMapping을 통해 parameter로 email과 비밀번호를 hashmap으로 받았다.

그후 service를 통해 로그인을 시도해 보고 결과에 따라 성공하면 session에 이름으로 세션값을 만들어 주고,

로그인에 실패할 경우 로그인 시도 페이지를 유지하게 한다.

 

이로써 mariaDB와 myBatis를 통해 웹개발을 하는 과정을 간단히 알아봤다.

'Spring & SpringBoot' 카테고리의 다른 글

MockMVC  (0) 2023.01.13
SpringBoot JPA 사용하기  (0) 2022.12.30
SpringBoot Swagger UI사용하기  (0) 2022.12.19
Spring AOP  (0) 2022.12.16
SpringBoot 이전 페이지 URL가져오기  (0) 2022.12.09
    'Spring & SpringBoot' 카테고리의 다른 글
    • SpringBoot JPA 사용하기
    • SpringBoot Swagger UI사용하기
    • Spring AOP
    • SpringBoot 이전 페이지 URL가져오기
    Gyuseok
    Gyuseok

    티스토리툴바