객체 관계 매핑(ORM)은 데이터베이스-객체 지향 프로그래밍 언어 간의 호환되지 않는 데이터를 변환하는 프로그래밍 기법이다.(출처.위키백과)
쉽게 말하자면 ORM을 활용해서 각 데이터베이스에 맞는 SQL 쿼리를 작성하지 않고 자바코드로 DB의 데이터를 다룰 수 있도록 해주는 기술이다.
이름에서 나타나듯 객체(Entity)와 데이터베이스의 테이블을 자동으로 매핑해줘서 개발자가 직접 DB에서 SQL을 수정하지 않아도 클래스의 속성을 수정하면 테이블의 컬럼도 이에 대응해 내용이 변경된다.
이번에 일정 관리 앱에 사용했던 JPA는 ORM을 활용하기 위한 인터페이스의 집합이다.
Product Table 有JPA Entity로 매핑된 클래스@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int price;
//getter, setter 생략
}
🅿️ JpaRepository를 상속받아 ProductRepository를 작성하기
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Long> {
}
🅿️ ProductRepository에 특정 금액 이상인 상품을 조회하는 메서드 추가하기
Repository에 추가 기능 메서드를 작성하려면 아래 규칙에 맞게 작성해야 한다.
| 추가 기능 메서드 | 기능 |
|---|---|
| findBy + 컬럼명 | 쿼리를 요청하는 메서드임을 알려준다. |
| countBy + 컬럼명 | 쿼리 결과 레코드의 수를 요청하는 메서드임을 알려준다. |
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findByPriceGreaterThanEqual(standardPrice);
}
위에 보면 findByPriceGreaterThanEqual이 적혀있는데
findBy + 컬럼명(Price) + 이상(GreaterThan) 과 같이 규칙에 맞게 적었다.
가격 컬럼에서 변수의 금액 이상을 갖는 가격을 모두 출력한다는 의미다.
Repository 메서드 작성 규칙 참고