# 상품 리포지토리 개발

기능 구현

* 상품 등록, 상품 수정 : save(Item item)\
  if(item.getId() == null) : JPA에 저장하기 전에는 id값이 없기 때문에 처음 생성하는 객체이면 일단 DB에 item 저장한다.(영속성 컨텍스트에 등록 em.persist(item) )\
  else : id 가 있으면 이미 데이터베이스에 저장된 엔티티를 수정한다고 보고, merge() 를 실행!

  ```java
  public void save(Item item){
          //JPA에 저장하기 전까지는 id값이 없다.새로 생성하는 객체라는 뜻
          if(item.getId() == null){//처음에는 id라는 게 없기 때문에.
              em.persist(item);
          } else{//이미 DB에 등록된 것이라는 뜻.
              em.merge(item);
          }
      }
  ```
* 상품 조회\
  findOne(Long id) : EntityManager.find(Item.class,id) 이용\
  findAll() : 쿼리문 작성, getResultList()로 리스트 반환

```java
package jpabook.jpashop.repository;

import jpabook.jpashop.domain.Item.Item;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import java.util.List;

@Repository
@RequiredArgsConstructor
public class ItemRepository {
    private final EntityManager em;

    public void save(Item item){
        //JPA에 저장하기 전까지는 id값이 없다.새로 생성하는 객체라는 뜻
        if(item.getId() == null){//처음에는 id라는 게 없기 때문에.
            em.persist(item);
        } else{//이미 DB에 등록된 것이라는 뜻.
            em.merge(item);
        }
    }
    public Item findOne(Long id){
        return em.find(Item.class,id);
    }
    public List<Item> findAll(){
        return em.createQuery("select i from Item i",Item.class)
                .getResultList();
    }
}

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://heunnajo.gitbook.io/jpa/5./undefined-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
