■ SPRING REVIEW & PRACTICE/INDIVISUAL

Preparation for Second Assignment

JH 2024. 8. 24. 21:57

 

  • Decide on a project name.

 

  • Create a file to work on, name it with your project name, and save it.

 

  • Open IntelliJ, click on "New Project," and select the latest version of Spring Boot.

 

  • Add the following Dependencies and click 'Create':
    1. Lombok
    2. Spring Web
    3. Thymeleaf
  • After creating a repository on GitHub, enter the following commands in Terminal:
    1. git init
    2. git remote add origin [your-repository-url]
    3. git branch -M main
      git --version -> if you want to check version
  • Create the following packages:
    1. controller
    2. dto
    3. service
    4. repository
    5. entity
  • In build.gradle, add the following two lines at the top of the dependencies section and click the elephant icon:
    Copy code
    // JPA implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    // MySQL runtimeOnly 'com.mysql:mysql-connector-j'

 

  • Click on resources > application.properties and paste the following content:
    Copy code
    # spring.application.name=[ProjectName]
    spring.datasource.url=jdbc:mysql://localhost:3306/[ProjectName]
    spring.datasource.username=root
    #spring.datasource.password= -> No password, but if there is one, add # to hide it spring.
    datasource.driver-class-name=com.mysql.cj.jdbc.Driver

    spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.show_sql=true spring.jpa.properties.hibernate.format_sql=true
    spring.jpa.properties.hibernate.use_sql_comments=true

 

  • Download MySQL via Homebrew and initialize the database:

    If MySQL is not installed(start from #1)
    1. Open iTerm
    2. mysql --version
    3. mysql.server start
    4. which mysql
    5. brew install mysql
    6. Once the download is complete:
    If MySQL is already installed(start from #7 and open iTerm)
    7) mysql.server start
    8) mysql -u root to confirm access to MySQL
    9) create database [database-name];
    10) show databases;
    11) Password setup can be done later (it’s not required immediately, but set it if needed).
    12) If you see a table, it was successful.


  • Create the database in IntelliJ:
    1. Click on Data Source
    2. Click on MySQL
    3. For user, enter root
    4. Leave the password field empty
    5. Database: [Project Name]
    6. Click Test Connection
    7. If successful, click Apply
    8. Click Create
  • To view the database, click on the DB icon in IntelliJ, navigate to tables, and click on them.
    • If you want to create additional tables, add annotations in the entity class
      @Table(name = "[table-name]")
       
       
  • Create the appropriate classes and interfaces in each package:
    1. controller:
      [ProjectName]Controller
    2. dto:
      • [ProjectName]RequestDto
      • [ProjectName]ResponseDto
    3. entity:
      • [ProjectName]
      • Timestamped
    4. repository: (This should be an interface, not a class)
      • [ProjectName]Repository
    5. service:
      • [ProjectName]Service

 

  • After writing the code, run it to check for errors.

 

  • Open Postman:
    1. In New Collection, click the ... button and then click Add Request
    2. For POST:
      • Use the URL http://localhost:8080/api/[ProjectName]
      • Select Body -> raw -> write -> send
        {
         "user"= "hi",
         "title" = "hi",
         "description" = "hi"
        }
      • Check the database in IntelliJ
      • Save the request in Postman
      • Click Save as Example and name it if desired

    3. For GET:
      • Use the URL http://localhost:8080/api/[ProjectName]/[start-number]
      • Click send
    4. For PUT:
      • Use the URL http://localhost:8080/api/[ProjectName]/[start-number]
      • Select Body -> raw -> modify as needed -> send
      • Check the database in IntelliJ to ensure changes are saved
      • Save the request in Postman
      • Click Save as Example and name it if desired
    5. For DELETE

 

  • Commit to Git:
    1. Commit from IntelliJ
      • Click all changed files in green
      • Include any unversioned files if they appear
      • Add a commit message and commit
    2. In Terminal, run git push -u origin main (check for any error messages if needed)
    3. Check your GitHub repository to confirm the commit.
 
 

 


 

 

0. 과제/프로젝트명 정하기

 

1. 작업해서 프로젝트 이름 넣어서 저장할 파일 만들기

 

2. intellJ 오픈해서 뉴 프로젝트 스프링부트 최신버전 클릭

 

3. 아래 Dependencies 추가 후 'create' 클릭

1) Lombok

2) Spring Web

3) Thyme Leaf

 

4. 깃허브에서 레파지토리 만든 후 Terminal에 차례대로 입력

1) git init

2) git remote add origin 나의 레파지토리주소

3) git branch -M main

 

참고로 git 다운로드 되어있는지 확인방법
git --version

5. 패키지 만들기

1) controller

2) dto

3) service

4) repository

5) entity

 

6. build.gradle 에서 dependencies 부분에 아래 두줄 맨 위에 추가하고 코끼리 아이콘 클릭

 

// JPA implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

 

// MySQL runtimeOnly 'com.mysql:mysql-connector-j'

 

7. resources > application.properties click 해서 아래 통채로 붙여넣기

 

이때 application.properties 파일을 application.yml로 첫번째 과제에 이렇게 바꿨는데 이유는 모름 -> 알아보기

여기 아래부터 붙여넣고 맞는 프로젝트 이름 설정 

# spring.application.name=프로젝트이름

 

spring.datasource.url=jdbc:mysql://localhost:3306/프로젝트이름

spring.datasource.username=root

#spring.datasource.password= -> 비밀번호 없으니! 있으면 앞에 # 넣어서 가려주기

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update

 

spring.jpa.properties.hibernate.show_sql=true

spring.jpa.properties.hibernate.format_sql=true

spring.jpa.properties.hibernate.use_sql_comments=true

 

8. mySQL brew 로 다운받고 데이터베이스 초기 만드는 법

 

*만약 다운로드 안받아져 있으면

1) iTerm 열기

2) mysql --version 3

) mysql.server start

4) which mysql

5) brew install mysql

6) 다운로드 다 되면

*만약 다운로드 되어있으면

7) mysql.server start

8) mysql -u root -> mysql 로 들어온걸 확인 하기

9) create database 파일이름;

10)show databases;

11) 비밀번호 설정은 나중에 (굳이 안넣어도 되는데 해야된다면 그때 설정하는걸로)

12) 표같은거 나오면 성공

 

8. intelliJ 에서 database 만들기 (=Query console)

1) Data source 클릭

2) mySql 클릭

3) user에 root

4) 비밀번호 비워놓기

5) Database: 프로젝트이름

6) Test connection 클릭

7) 성공뜨면 apply

8) create

9) 조회는 intelliJ에서 db 누르고 클릭하며 들어가서 tables1 클릭
10) 혹시 table 여러개 더 만들고 싶다면 entity에 들어가서 애너테이션 넣어주기
@Table(name = "이름정해서넣주기")

 

8. 각 패키지 안에 맞는 클래스 및 인터페이스 만들기

1) controller:
프로젝트이름Controller

2) dto:
프로젝트이름: RequestDto
프로젝트이름: ResponseDto

3) entity: 
프로젝트이름 -> 선언해주는것
Timestamped

4) repository: 여기만 클래스가 아닌 인터페이스
프로젝트이름Repository

5) service:
프로젝트이름Service

 

9. 코드작성 후 재생해서 에러 없는지 확인

 

10. 포스트맨 열기

1) New collection 에서 ... 버튼 누르고 add request 누르기

2) post -> http://localhost:8080/api/프로젝트이름 -> Body -> raw -> 작성 -> send -> intelliJ에서 db 확인 -> 포스트맨에서 save-> save as example 두버튼 클릭 -> 이름도 원하면 바꾸기

{
"username": "Joohee",
"title": "Test",
"description": "Test"
}

 

3) get -> http://localhost:8080/api/프로젝트이름/숫자1부터시작 -> send

4) put -> http://localhost:8080/api/프로젝트이름/숫자1부터시작-> Body -> raw -> 수정하고싶은거 수정 -> send -> intelliJ에서 db 에 수정했던거 저장 잘 되었는지 확인 -> 포스트맨에서 save-> save as example 두버튼 클릭 -> 이름도 원하면 바꾸기

5) delete

 

11. git commit 하기

1) intelliJ 에서 commit 하기 초록색들 changed 된 파일들 모두 클릭 이때 unversioned files 도 나오면 그것들도 다 클릭
2) 메세지 넣어주고 commit

3) 터미널가서 git push -u origin main (만약 오류메세지 확인하고 싶으면?)

4) 나의 깃 레파지토리 가서 깃 커밋되었는지 확인

 


참고
첫번째 스프링 개인과제 준비 했던 과정도 추가 게시

1. 깃 세팅 

  1. 먼저 레파지토리 새로 생성하기
  2. iTerm 열어서 현재 화면에서 나가기 exit
  3. cd Documents
  4. ls
  5. cd spring
  6. ls
  7. cd week1
  8. ls
  9. cd spirngfirsthomework
  10. 성공하면
  11. git init -> 맥북은 알아서 해주지만 그래도 잊지말고 하기
  12. git add.
  13. git commit -m "levelone"
  14. git branch -M main
  15. git remote add origin 깃헙레파지토리주소
  16. git push -u origin main
  17. 하면 처음 셋팅 끝이고
그 이후로 두번째 단계부터 올릴 때는
  1. git add .
  2. git commit -m "메세지넣기"
  3. git push origin main



2. SQL 이름 바꾸는 방법 

sql 이름 바꾸는 방법:Database
@localhost 우클릭
New
Query Console
create database 바꾸고싶은이름
바로 위에 재생버튼
entity 에 기본적인거 채우기
에러방지하기 위해 application.properties 에서
spring.jpa.hibernate.ddl-auto=create-drop -> 이렇게 create-drop 으로 바꾸기 spring.jpa.properties.hibernate.format_sql=false -> 이부분은 true에서 false 로 바꾸기
Applicationa 메인가서 재생버튼눌러보고 만약 에러뜨면
kill $(lsof -t -i:8080)  터미널에 넣어서 포트 삭제해주기
그리고 다시 재생버튼 눌러서 잘 돌아가는지 확인 하고
데이터베이스 눌러서 테이블 들어가서 테이블 생긴지 확인하기