νμ κ΄λ¦¬ μμ
2. νμ λλ©μΈκ³Ό 리ν¬μ§ν 리 λ§λ€κΈ°
1) νμ λλ©μΈ λ§λ€κΈ°
- damain ν¨ν€μ§ μμ±
- Member ν΄λμ€ μμ±: μꡬμ¬ν λ°μ΄ν° μ μνλ€.
package hello.hello.spring.domain;
public class Member {
private Long id; // μμ€ν
μ΄ μ μ₯ν μμμ κ°
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;
}
}
2) 리ν¬μ§ν 리 λ§λ€κΈ°
- repository ν¨ν€μ§ μμ±: νμ κ°μ²΄λ₯Ό μ μ₯νλ€.
- MemberRepository μΈν°νμ΄μ€ μμ±: νμ μ μ₯ λ° μ‘°ν κΈ°λ₯μ λ§λ λ€.
- MemoryMemberRepository ν΄λμ€ μμ±: λ©λͺ¨λ¦¬ κΈ°λ° κ΅¬ν체μ΄λ€.
package hello.hello.spring.repository;
import hello.hello.spring.domain.Member;
import java.util.List;
import java.util.Optional;
public interface MemberRepository {
Member save(Member member);
Optional<Member> findById(Long id);
Optional<Member> findByName(String name);
List<Member> findAll();
// Optional: nullμ λ°νν λ κ°μΈμ λ°ννλ€.
}
package hello.hello.spring.repository;
import hello.hello.spring.domain.Member;
import java.util.*;
public class MemoryMemberRepository implements MemberRepository {
// λμμ± λ¬Έμ κ° κ³ λ €λμ΄ μμ§ μμ
// μ€λ¬΄μμλ ConcurrentHashMap, AtomicLong μ¬μ© κ³ λ €
private static Map<Long, Member> store = new HashMap<>();
private static long sequence = 0L;
@Override
public Member save(Member member) {
// nameμ μ΄λ―Έ κ³ κ°μ΄ λ±λ‘ν μνμ΄λ€.
member.setId(++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) {
// values().stream(): value κ°μ loop νλ€.
// filter(member -> member.getName().equals(name)): λλ€ νμμΌλ‘ νν°λ§νλ€.
// findAny(): νλλΌλ μ°ΎμΌλ©΄ Optional μνλ‘ λ°ννλ€.
return store.values().stream()
.filter(member -> member.getName().equals(name))
.findAny();
}
@Override
public List<Member> findAll() {
// μ€λ¬΄μμλ Listλ₯Ό λ§μ΄ μ¬μ©νλ€.
return new ArrayList<>(store.values());
}
}