Home [Spring Security JWT] 회원정보 테이블 작성
Post
Cancel

[Spring Security JWT] 회원정보 테이블 작성

이 게시글은 유튜브 개발자 유미님의 무료강의 스프링 시큐리티 JWT 5 : DB연결 및 Entity 작성을 수강하며 공부한 내용을 담고있습니다.
이 게시글은 공부한 내용을 제가 보기 편하게 정리한 내용이므로 정확한 정보는 위 영상을 시청해주세요.

이 게시글은 기본적인 Spring 기본 실습을 해봤다는 가정하에 기초적인 설명은 생략되어 있습니다.
또한 실습을 따라가며 기본적인 JWT 사용방법을 학습하기에 상세한 원리와 설명은 없는 경우가 있습니다.

개요

JWT 를 실습할 데이터가 필요하므로 간단한 회원정보를 담는 DB 를 작성한다.

의존성 주석 해제

1
2
//	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
//	runtimeOnly 'com.mysql:mysql-connector-j'

처음에 build.gradle 에서 주석처리 했던 의존성을 주석해제한다.
build.gradle 은 수정이 완료되면 코끼리 버튼을 눌러서 적용해야한다.

DB 연결 세팅

1
2
3
4
5
6
7
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/JwtStudy?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=password

spring.jpa.hibernate.ddl-auto=none
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

DB 를 설치하고 resources > application.properties 에 위 코드를 작성해준다.
spring.datasource.url 에 DB IP주소:port번호 를 작성하고, 사용할 DB 스키마 이름을 작성한다.
나는 스키마 이름을 JwtStudy 라고 결정했다.

본인이 h2 DB 또는 오라클을 이용중이라면 그것에 맞게 spring.datasource.driver-class-name 를 수정하면 되고, localhost 가 아닌 다른 ip에 위치한 DB 를 사용한다면 그거에 맞게 수정하면 된다.

Entity

idusernamepasswordrole
    

위처럼 회원정보를 저장하는 table 이 있다고 생각하자.
이 테이블을 대응 되는 entity 클래스를 만들 것이다.
우선 entity 패키지를 만들고 그 안에 UserEntity 클래스를 작성하자.
그리고 아래 코드를 작성한다.
사진1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Entity
@Getter
@Setter
public class UserEntity {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    
    private String username;
    private String password;
    
    private String role;
}

일단 @Entity 를 붙여 이 클래스가 DB 에 연결할 수 있도록 한다.
table 에 해당 되는 각 column 을 필드로 매칭해준다.
@GeneratedValue(strategy = GenerationType.IDENTITY) 는 mysql 에서 auto increment 와 동일한 의미다.
@Id, @GeneratedValue 등과 같은 어노테이션을 붙여 column 의 제약조건, 속성을 명시한다.

Repository interface

마찬가지로 repository 패키지를 만들고 UserRepository 인터페이스를 생성하고 아래 코드를 작성한다.

1
2
public interface UserRepository extends JpaRepository<UserEntity, Integer> {
}

JpaRepository 를 상속받을 때 제네릭 타입에는 관리할 엔티티(UserEntity) 와 그 엔티티의 기본 키(ID) 의 자료형(Integer) 를 작성해주면 된다.

생성

일단 기본적인 뼈대는 여기까지 만들고 테이블을 생성한다.
application.properties 로 가서 spring.jpa.hibernate.ddl-auto= 값을 create 로 설정하고 프로젝트를 실행한다.

1
2
// 프로젝트가 실행될 때 마다 table 을 생성(이미 존재하면 삭제 후 생성)
spring.jpa.hibernate.ddl-auto=create

그러면 JPA 가 @Entity 들을 참고하여 ddl 문을 작성하고 수행한다.
정상적으로 수행이 되면 mysql 에 접속해 테이블이 제대로 만들어졌는지 확인한다.
만들어진걸 확인한 후 create 를 다시 none 으로 바꾼다.

오류

나 같은 경우 JwtStudy 스키마가 없다고 오류가 발생했다. 이 경우 직접 터미널을 열어 mysql 을 접속하고 create database 를 통해 직접 생성하거나 application.properties 를 수정해주면 된다.

1
2
3
4
5
// 수정 전
spring.datasource.url=jdbc:mysql://localhost:3306/JwtStudy?useSSL=false&useUnicode=true&

// 수정 후
spring.datasource.url=jdbc:mysql://localhost:3306/JwtStudy?createDatabaseIfNotExist=true&useSSL=false&useUnicode=true&

createDatabaseIfNotExist=true 를 추가해주어 스키마가 없는 경우 자동으로 생성하도록 한다.



이전 포스팅 : Config 클래스 작성
다음 포스팅 : 회원가입 로직 작성

This post is licensed under CC BY 4.0 by the author.

[Spring Security JWT] Config 클래스 작성

[Spring Security JWT] 회원가입 로직 작성