Java/Spring
[Spring] 게시판 만들기 #2
상도동 카르마
2022. 11. 13. 14:17
What to do?
Jpa 설정하기
- My SQL 설치
- JPA 설정
- CRUD TEST 코드 작성
My SQL 설치
My SQL Community 버전을 다운 받아서 설치해주자
데이터 베이스를 board라는 이름으로 생성
create database board;
use board;
테이블 생성하기
Entity 코드를 작성한 파일에 오른쪽 마우스를 클릭하면
Show DDL이라는 메뉴가 나온다.
자동으로 DDL을 작성해준다.
user_account, article, comment 테이블도 동일하게 DDL을 만들어서
MySQL 터미널에 복붙 해주자.
DB 연결 설정
application.yaml파일을 다음과 같이 작성해주자
spring:
datasource:
url: jdbc:mysql://localhost:3306/board
username: root
password: 1221
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
open-in-view: false
defer-datasource-initialization: true
hibernate.ddl-auto: create
show-sql: true
properties:
hibernate.format_sql: true
hibernate.default_batch_fetch_size: 100
sql.init.mode: always
data.rest:
base-path: /api
detection-strategy: annotated
잘 연결되는지 확인하기 위해 Test Connection을 해보자.
성공한 것을 보니 잘 연결된 것 같다.
예제 데이터 만들기
mockaroo라는 사이트를 이용해서 샘플 데이터를 대량으로 만들어보자.
다운받은 파일에는 insert query들이 담겨있다.
이걸 data.sql에 붙여넣고, run을 돌려보면 잘 돌아간다.
예제 데이터 쿼리
Repository 코드 작성
@Repository
public interface ArticleRepository extends JpaRepository<Article, Long> {
}
@Repository
public interface CommentRepository extends JpaRepository<Comment, Long> {
}
CRUD 테스트 코드
Repository 코드에서 단축키 Ctrl+Shift+t를 누르면 테스트 코드 작성하는 탭이 나온다.
Jpa Test라는 이름으로 Repository 테스트 파일을 만들자.
간단한 CRUD 테스트 코드를 작성하였다.
@DisplayName("Jpa CRUD")
@Import(JpaConfig.class)
@DataJpaTest
class JpaTest {
@Autowired private final ArticleRepository articleRepository;
@Autowired private final CommentRepository commentRepository;
public JpaTest(@Autowired ArticleRepository articleRepository, @Autowired CommentRepository commentRepository) {
this.articleRepository = articleRepository;
this.commentRepository = commentRepository;
}
@Test
@DisplayName("SELECT ALL")
void select_all(){
//given → nothing
//when → find all
List<Article> articles = articleRepository.findAll();
//then → not null
assertThat(articles)
.isNotNull();
}
@Test
@DisplayName("INSERT")
void insert(){
//given → count
long previousSize = articleRepository.count();
Article recordToInsert = Article.of("new title", "new content", "new hashtags");
//when → save new data
List<Article> articles = articleRepository.findAll();
articleRepository.save(recordToInsert);
//then → count = previous count + 1
assertThat(articleRepository.count())
.isEqualTo(previousSize+1);
}
@Test
@DisplayName("UPDATE")
void update() {
//given → record to update
Article recordToUpdate = articleRepository.findById(1L).orElseThrow();
//when → update data
recordToUpdate.setTitle("updated title");
recordToUpdate.setHashtags("updated hashtag");
Article savedRecord = articleRepository.saveAndFlush(recordToUpdate);
//then → check updated field
assertThat(savedRecord)
.hasFieldOrPropertyWithValue("title", "updated title")
.hasFieldOrPropertyWithValue("hashtags", "updated hashtag");
}
@Test
@DisplayName("DELETE")
void delete() {
//given → record to delete
Article recordToDelete = articleRepository.findById(1L).orElseThrow();
Long previousCount = articleRepository.count();
//when → delete record
articleRepository.delete(recordToDelete);
//then → count = previous count - 1
assertThat(articleRepository.count())
.isEqualTo(previousCount-1);
}
}