출처 : 인프런 강의 참고 (코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술)
우클릭 > Generate > Getter and Setter
package hello.hellospring.domain;
public class Member {
private Long id; // 시스템이 정하는 아이디 값 (사용자지정x)
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import java.util.List;
import java.util.Optional;
public interface MemberRepository {
Member save(Member member); //회원 저장 후 저장된 회원 반환
Optional<Member> findById(Long id); // 저장소에서 findById로 id값을 찾아오기
Optional<Member> findByName(String name); // 저장소에서 findByName으로 name값을 찾아오기
List<Member> findAll(); // 지금까지 저장된 모든 회원 정보 반환
}
package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import java.util.*;
public class MemoryMemberRepository implements MemberRepository {
private static Map<Long, Member> store = new HashMap<>();
private static long sequence = 0L;
@Override
public Member save(Member member) {
member.setId(++sequence); // sequence 값 하나를 올려줌
store.put(member.getId(), member);
return member;
}
@Override
public Optional<Member> findById(Long id) {
// null이 반환될 경우가 있을 경우 Optional로 감싼다.
return Optional.ofNullable(store.get(id));
}
@Override
public Optional<Member> findByName(String name) {
// java lambda code
// store에 있는 getName 과 파라미터의 name이 같은지 확인 후 같으면 반환
return store.values().stream()
.filter(member -> member.getName().equals(name))
.findAny();
}
@Override
public List<Member> findAll() {
return new ArrayList<>(store.values());
}
public void clearStore(){
store.clear();
}
}
package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import java.util.List;
import static org.assertj.core.api.Assertions.*;
class MemoryMemberRepositoryTest {
MemoryMemberRepository repository = new MemoryMemberRepository();
@AfterEach
public void afterEach(){
repository.clearStore();
}
@Test
public void save(){
Member member = new Member();
member.setName("spring");
repository.save(member);
Member result = repository.findById(member.getId()).get();
// 검증
assertThat(member).isEqualTo(result);
}
@Test
public void findByName(){
Member member1 = new Member();
member1.setName("spring1");
repository.save(member1);
Member member2 = new Member();
member2.setName("spring2");
repository.save(member2);
Member result = repository.findByName("spring1").get();
assertThat(result).isEqualTo(member1);
}
@Test
public void findAll(){
Member member1 = new Member();
member1.setName("spring1");
repository.save(member1);
Member member2 = new Member();
member2.setName("spring2");
repository.save(member2);
List<Member> result = repository.findAll();
assertThat(result.size()).isEqualTo(2);
}
}
@Test : Test를 지원하는 annotation
Junit은 각각의 테스트(method단위)가 서로 영향 주지 않고 독립적으로 실행되는 것을 원칙으로함.
@afterEach : 하나의 method가 끝난 후 실행되는 콜백함수
해당 클래스 안에 있는 각각의 method가 실행된 후 repository에 있는 데이터를 지우고 새로 생성하는 것을 원칙으로 한다(method 단위 독립적 실행)
assertThat() : JUnit에서 제공하는 테스트 코드에서 검증할 때 활용
assertThat(실제값, 기대값)
or assertThat(실제값).isEqualTo(기대값)
package hello.hellospring.service;
import hello.hellospring.domain.Member;
import hello.hellospring.repository.MemberRepository;
import hello.hellospring.repository.MemoryMemberRepository;
import java.util.List;
import java.util.Optional;
public class MemberService {
private final MemberRepository memberRepository;
public MemberService(MemoryMemberRepository memberRepository){
this.memberRepository = memberRepository;
}
/**
*회원가입
*/
public Long join(Member member){
// 같은 이름이 있는 중복 회원X
validateDuplicateMember(member); // 중복 회원 검증
memberRepository.save(member); // 통과하면 저장
return member.getId();
}
private void validateDuplicateMember(Member member){
memberRepository.findByName(member.getName())
.ifPresent(member1 -> {
throw new IllegalStateException("이미 존재하는 회원입니다.");
});
}
/**
* 전체 회원 조회
*/
public List<Member> findMembers(){
return memberRepository.findAll();
}
/**
* 한명 회원 조회
*/
public Optional<Member> findOne(Long memberId){
return memberRepository.findById(memberId);
}
}
ctrl + shift + T
package hello.hellospring.service;
import hello.hellospring.domain.Member;
import hello.hellospring.repository.MemoryMemberRepository;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.*;
class MemberServiceTest {
MemberService memberService;
MemoryMemberRepository memberRepository;
@BeforeEach
public void beforeEach(){
memberRepository = new MemoryMemberRepository();
memberService = new MemberService(memberRepository);
}
@AfterEach
public void afterEach(){
memberRepository.clearStore();
}
@Test
void join() {
// given
Member member = new Member();
member.setName("spring");
//when
Long saveId = memberService.join(member);
//then
Member findMember = memberService.findOne(saveId).get();
Assertions.assertThat(member.getName()).isEqualTo(findMember.getName());
}
@Test
public void DuplicateJoinException(){
// given
Member member1 = new Member();
member1.setName("spring");
Member member2 = new Member();
member2.setName("spring");
//when
memberService.join(member1);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> memberService.join(member2));
assertThat(e.getMessage()).isEqualTo("이미 존재하는 회원입니다.");
}
}
package hello.hellospring.controller;
public class MemberForm {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Controller
public class MemberController {
private final MemberService memberService;
@Autowired
public MemberController(MemberService memberService) {
this.memberService = memberService;
}
@GetMapping("/members/new")
public String createForm(){
return "members/createMemberForm";
}
@PostMapping("/members/new")
public String create(MemberForm form){
Member member = new Member();
member.setName(form.getName());
memberService.join(member);
return "redirect:/";
}
@GetMapping("/members")
public String list(Model model){
List<Member> members = memberService.findMembers();
model.addAttribute("members", members);
return "members/memberList";
}
}
return "members/createMemberForm";
: "members/createMemberForm.html" 파일을 찾음.findMembers()
: 모든 member를 가져옴...
<table>
<thead>
<tr>
<th>#</th>
<th>이름</th>
</tr>
</thead>
<tbody>
<tr th:each="member : ${members}">
<td th:text="${member.id}"></td>
<td th:text="${member.name}"></td>
</tr>
</tbody>
</table>
...
${member}
: ${model안에 있는 값}
${member.id}
: member.getId${member.name}
: member.getName서버를 내려버리면 메모리에 저장되는 방식이여서 기존에 데이터가 모두 삭제되므로
데이터를 Database에 저장