공부 기록
[프로젝트] JPA 이용하여 CRUD하기 본문
✅ 프로젝트 적용
0. Docker와 mariadb설치
[맥북/맥 Mac] 도커(Docker)로 MariaDB 설치하기
안녕하세요, 송아지할때 송아 김송아입니다. Docker Desktop을 설치하셨다면, 👉🏻 1분만에 설치하기 https://songacoding.tistory.com/56 우리는 맥/맥북 Terminal (또는 윈도우 cmd) 을 이용해서 Docker hub에 있는
songacoding.tistory.com
1-1. 의존성 추가
1-2. mariadb와 연결하기
2. Entity 수정
@Entity
@Getter //lombok 어노테이션 : 클래스 내 모든 필드의 Getter 메서드 자동 생성
public class Food {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private long foodId;
@Column(nullable = false, length = 50)
private String foodName;
@Column(nullable = false)
private int price;
@Column(nullable = false)
private String foodDescription;
}
3. Food Repository (Interface) 생성
인터페이스 생성 후 JpaRepository<Entity클래스, PK타입>을 상속하면 기본적인 CRUD 메서드가 자동으로 생성된다.
- JpaRepository는 PagingAndSortingRepository, QueryExampleExecutor 인터페이스 상속
- PagingAndSortingRepository는 CrudRepository 상속
- CrudRepository 엔터페이스서 기본적인 CRUD 메서드 제공
: save(), findById(), existsById(), count(), deleteById(), delete(), deleteAll()
- QueryByExampleExecutor 인터페이스에서 더 다양한 CRUD 메서드 제공
: findOne(), findAll(), count(), exists()
❗등록과 수정 메서드 : save()
save() 메서드가 호출될 때 save()는 2가지 일을 한다.
- 이 객체가 DB에서 가져오지 않은 새로운 객체인 경우 : insert문이 나오며 새로운 객체 저장
- 이 객체가 DB에서 가져온 적 있는 객체인 경우 : update문이 나가며 기존 데이터 저장
테스트 결과 FoodRepository에서 update 메서드를 따로 만들지 PATCH로 foodId가 포함된 객체를 넘겼을 경우 데이터가 수정되었고, POST로 foodId없이 새로운 객체를 넘긴 경우 새로운 데이터가 등록되었다.
📚 참고자료
- https://m.blog.naver.com/hj_kim97/222780110215
- https://docs.spring.io/spring-data/jpa/reference/repositories/query-keywords-reference.html
- https://trace90.tistory.com/entry/SpringBoot-MariaDB-JDBCDocker
- https://youtu.be/AHLbqZ4G5n4?si=sULIPWKe6Qv_swDU
- https://www.inflearn.com/questions/778804/comment/241583
'프로그래밍 > 프로젝트' 카테고리의 다른 글
[프로젝트] Entity ↔ DTO 변환 계층 선택 (1) | 2024.01.30 |
---|---|
[프로젝트] builder와 BeanUtils.copyProperties() (0) | 2024.01.30 |