본문 바로가기

web/Spring

Springboot h2 초기 세팅 (연결 ~ 테스트)

0. 프로젝트 생성 -> dependencies 설정되고있도록 일단 프로젝트의 build.gradle 로드

 

0-2. application.properties -> application.yml로 변경

git ignore에 *.yml 등록(안하면 db 털림)

git add .

git commit -"프로젝트 생성"

git push

 

yml이 git에 올라가지 않은 것 확인 *여기서 static이 안들어간건 걱정 ㄴㄴ 폴더 안ㅇ ㅔ파일이 없어서 그럼

 

 

H2 세팅

1. 데스크탑 h2 위치

C:\my2023programs\H2\bin

 

2. h2.bat 실행

 

3. url의 ip주소를 localhost로 변경

(이 방법으로 안 되면 그냥 안 바꾸고 ip로 시도)

 

4. JDBC URL 변경

jdbc:h2:C:\my2023programs\toy\league_of_legends/lol_db

jdbc:h2:{db가 있을 경로}/{db이름}

 

5.좌측상단 연결끊기 눌러서 연결끊고, 다음 나오는 페이지에서 jdbc url tcp 접속으로 바꾸고 복사 -> 이게 db접속주소임

jdbc:h2:tcp://localhost/C:\my2023programs\toy\league_of_legends/lol_db

jdbc:h2:tcp://localhost/{db경로}/{db이름}

(한번 들어가보기)

 

6. application.yml 기본 세팅

spring:
  datasource:
    url: jdbc:h2:tcp://localhost/C:\my2023programs\toy\league_of_legends/lol_db
    username: sa
    password:
    driver-class-name: org.h2.Driver
logging: #log4j setting
  level:
    root: info

 

 

---

templates/user.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div th:each="user:${users}">
  <h1 th:text="|${user.id} ${user.nickname}|"></h1>
</div>

<h2 th:text="${oneUser}"></h2>
</body>
</html>

git commit 임시 유저 템플릿 생성


User.java

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter @Setter @ToString
public class User {
    int id;
    String email;
    String nickname;
}

git commit 임시 유저 도메인 생성


UserMapper.java


import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    //insert문 실행(회원입력)
    @Insert("INSERT INTO temp_user(user_email,user_nickname) VALUES('aa@aa.a','jyanoos')")
    int saveUser();

    //select문 실행(회원조회)
    @Results(id = "UserMap",value = {
            @Result(property = "id",column="user_id"),
            @Result(property = "email", column = "user_email"),
            @Result(property = "nickname",column = "user_nickname")
    })
    @Select("SELECT * FROM temp_user")
    List<User> listUser();


    //동적쿼리 ${}로 감싸면 ''포함 안되고, #{}로 감싸면 ''이 자동으로 포함됩니다
    @ResultMap("UserMap")
    @Select("SELECT * FROM temp_user where user_id=${id} AND user_email=#{email}")
    User showUser(@Param("id")int id, @Param("email")String email);

    @Select("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'TEMP_USER'")
    int tempUserTblExistCheck();//있으면 1 없으면 0

    //temp_user라는 이름의 테이블이 없다면 생성함
    @Update("CREATE TABLE IF NOT EXISTS temp_user(user_id bigint PRIMARY KEY auto_increment, user_email VARCHAR(255), user_nickname VARCHAR(255))")
    int createTempUserTblIfNotExist();//int를 리턴하나 항상 0이 나와서 무의미

}

git -> 임시 유저 매퍼 생성


UserService.java

import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class UserService {
    private final UserMapper userMapper;


    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    //회원입력
    public void joinUser(){
        userMapper.saveUser();

    }

    //회원리스트조회
    public List<User> showUser(){
        return userMapper.listUser();
    }

    //회원조회
    public User showOneUser(int id, String email){
        return userMapper.showUser(id,email);
    }

}

git -> 임시 유저 서비스 생성


UserController.java


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@Slf4j
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/test")
    public String join(Model model){
        userService.joinUser(); //회원 입력
        List<User> users = userService.showUser(); //회원조회
        model.addAttribute("users",users);


        int id = 1;
        String email = "aa@aa.a";
        User oneUser = userService.showOneUser(id,email);
        model.addAttribute("oneUser",oneUser);

        log.info("참참참");
        return "user";
    }
}

git -> 임시 유저 컨트롤러 생성


StartupApplicationListener.java  --> 프로젝트가 실행되고 모든 빈이 생성되고 예약 행동 함

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RequiredArgsConstructor
//모든 빈이 생성되고 의존성이 주입된 후 실행됨
public class StartupApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    private final UserMapper userMapper;


    public boolean setUp(){
        int tempUserTblExist = userMapper.tempUserTblExistCheck();
        log.info("tempUserTblExist is "+ tempUserTblExist);//테이블이 있으면 1, 없으면 0이 뜬다
        if(tempUserTblExist==0){
            log.info("temp_user 테이블이 없어서 생성합니다");
            int tempUserTblIfNotExist = userMapper.createTempUserTblIfNotExist();//이건 항상 0 리턴 - 활용 불가능
        }
        return true;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {//모든 빈이 생성되고 의존성이 주입된 후 실행됨
        setUp();

    }
}

git -> startup리스너 생성


Mainconfiguration.java  

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@ComponentScan

public class MainConfiguration implements WebMvcConfigurer  {
}

git -> cofiguration 생성


테스트 작성

build.gradle의 dependencies에 아래 코드 추가하고 다시 빌드

testImplementation("org.junit.vintage:junit-vintage-engine"){
   exclude group: "org.hamcrest",module:"hamcrest-core"
}

git -> test용 junit dependency 추가

 


UserServiceTest 생성(UserService 클래스에서 Ctrl shift t누르고 junit4로 바꾸고 확인)

 

UserServiceTest.java

import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.List;

@SpringBootTest
public class UserServiceTest {
    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(MainConfiguration.class);
    UserService userService = ac.getBean(UserService.class);

    @Test
    public void 임시테스트(){
        //given
        userService.joinUser();
        userService.joinUser();
        userService.joinUser();

        //when
        List<User> users = userService.showUser();
        // then
        Assertions.assertThat(users.size()).isEqualTo(3);//4로 바꿔보면 틀리게 나오는거 확인
    }

}

함 돌려보고 값 바꿔서 틀리나 확인하고 Git ㄱ ㄱ


UserMapperTest생성(UserMapper클래스에서 Ctrl shift t누르고 junit4로 바꾸고 확인)

 

UserMapperTest.java


import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.List;

@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class UserMapperTest {
    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(MainConfiguration.class);
    UserMapper userMapper = ac.getBean(UserMapper.class);

    @Test
    public void 매퍼테스트(){
        //given 두번 추가
        userMapper.saveUser();
        userMapper.saveUser();
        //when
        List<User> users = userMapper.listUser();

        // then
        Assertions.assertThat(users.size()).isEqualTo(2);//1로 바꾸면 틀리는 거확인
    }


}

함 돌려보고 값 바꿔서 틀리나 확인하고 Git ㄱ ㄱ