[ View 환경설정 ]
Spring에서 공식적으로 사용을 권장하는 thymeleaf 를 사용해서 View를 연동하도록 하자
프로젝트를 생성할때 이미 thymeleaf 를 추가해서 디펜덴시에 라이브러리가 추가되어있다.
Thymeleaf
템플릿 엔진의 일종.
html 태그에 속성을 추가해 페이지에 동적으로 값을 추가하거나 처리할 수 있다.
타임리프는 html태그를 기반으로 하여 th: 속성을 이용하여 동적인 View를 제공
장점 > Nature templates, 순수 HTML을 그대로 유지하면서도 뷰 템플릿을 사용할 수있다.
단점 > 2.x버전에서 < > 태그사용시 열고 닫고를 무조건 해줘야한다. (3.x버전부터 열고 닫고안 해도 사용가능)
스프링 부트 thymeleaf viewName 매핑
resources:templates/ +{ViewName} + .html
매핑시 + .html이 되어있기 때문에, controller에서 return 값에 "hello"라고만 작성해도 templates의 hello.html을 찾을 수 있다.
HelloController
@Controller
public class HelloController {
@GetMapping("hello")
public String hello(Model model){
model.addAttribute("data","hello!");
return "hello";
}
}
hello.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'안녕' + ${data}" >안녕하세요. 손님</p>
</body>
</html>
로컬로 실행해보면
다르게 사용하려면 templates 매핑을 변경하면 된다.
[ DB 설정 ]
데이터베이스는 H2를 사용한다.
h2와 연동하기위해 설정값을 넣어줘야하는데,
인텔리제이에 이미 생성된 application.properties 파일을 사용하거나, application.yml 파일을 새로 생성해서 설정값을 넣어주면된다.
여기서는 application.yml 파일을 생성해준다.
두 가지 방법의 작동은 크게 다를게 없는데,
yml 파일로 설정할 경우 계층적으로 나타낼 수 있기때문에 이해하기 쉽고, 간결하고 또 중복을 방지할 수 있다.
# 띄어쓰기가 좀 번거롭다.
spring:
datasource:
url: jdbc:h2:tcp://localhost/~/JDBC URL 이름
username: 유저네임
password: 비밀번호
driver-class-name: org.h2.Driver
jpa:
hibernate:
ddl-auto: create
properties:
hibernate:
# show_sql: true
format_sql: true
logging:
level:
org.hibernate.SQL: debug
org.hibernate.orm.jdbc.bind: trace
# 3.x 버전에서는 위와 같이, 2버전대는 다르다.
· spring.jpa.hibernate.ddl-auto : create > 애플리케이션 실행 시점에 테이블을 drop하고, 다시 생성한다.
· 모든 로그 출력은 가급적 로거를 통해 남겨야 한다.
- show_sql : System.out에 하이버네이트 실행 SQL을 남긴다.
- org.hibernate.SQL : logger를 통해 하이버네이트 실행 SQL을 남긴다.
이렇게 설정해놓고 실행되는지 test를 해보자!
회원 엔티티를 만들어준다.
@Entity
@Getter @Setter
public class Member {
@Id @GeneratedValue
private Long id;
private String name;
// Lombok을 사용해서 @Getter, @Setter로 받자
}
회원 레포지토리
@Repository
public class MemberRepository {
@PersistenceContext
private EntityManager em;
public Long save(Member member){
em.persist(member);
return member.getId();
}
public Member find(Long id){
return em.find(Member.class,id);
}
}
이렇게 만들어줬으면 test 메소드를 생성해주자.
ctrl + shift + t 단축키 >> 새 테스트 생성
테스트는 JUnit4로 변경, 확인
MemberRepositoryTest.java 가 생성된다.
@SpringBootTest // springboot로 테스트 할때
@RunWith(SpringRunner.class)
public class MemberRepositoryTest {
@Autowired MemberRepository memberRepository;
@Test
@Transactional
@Rollback(false) // test완료후 commit된 값을 다시 rollback
public void testMember() throws Exception{
//given
Member member = new Member();
member.setName("memberA");
// when
Long saveId = memberRepository.save(member);
Member findMember = memberRepository.find(saveId);
// then
Assertions.assertThat(findMember.getId()).isEqualTo(member.getId());
Assertions.assertThat(findMember.getName()).isEqualTo(member.getName());
Assertions.assertThat(findMember).isEqualTo(member);
}
}
테스트 실행하면 성공으로 뜬다.
근데 아쉽다. 로그를 더 보고싶다.
그래서 외부 라이브러리를 가져와서 추가해줬다.
https://github.com/gavlyukovskiy/spring-boot-data-source-decorator
여기서 지원해주는 spring boot datasource decorator를 사용한다.
build.gradle에 라이브러리 추가해주자 ( 스프링부트 버전에 맞게 가져오자 )
implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.9.0'
리프레쉬해주고 다시 테스트 실행해보면
뭐 대충 이런식으로 뜨는걸 확인할 수 있다!
DB연동 설정도 이렇게 끝 !
'spring boot > JPA' 카테고리의 다른 글
[ JPA ] 회원 도메인 개발 (0) | 2023.12.27 |
---|---|
[ JPA ] 영속성 컨텍스트 + 엔티티 매핑 (0) | 2023.12.21 |
[ JPA ] 엔티티 클래스 개발 (0) | 2023.12.14 |
[ JPA ] 도메인 분석 설계 (0) | 2023.12.13 |
[ JPA ] 프로젝트 생성 + 라이브러리 (0) | 2023.12.13 |