Entity란?
“DB 테이블과 연결되는 객체”
"상태와 비즈니스 규칙을 가진 객체"
역할
- DB 테이블 매핑
- 영속성 관리
- 비즈니스 상태 관리
참고 : https://record47584.tistory.com/3
JPA(Java Persistence API)에 대한 간단한 정리
JPA란?자바 객체와 데이터베이스를 연결해주는 기술DB를 객체처럼 다룰 수 있게 해주는 기술 JPA의 핵심 개념 1 : ORM(Object Relational Mapping)객체와 관계형 DB를 매핑하는 기술자바는 객체 지향이고 DB
record47584.tistory.com
프로젝트 구현
import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Entity
@Getter
@NoArgsConstructor
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int quantity;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "product_id")
private Product product;
public Order(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
}
package com.example.crudproject.entity;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Entity
@Getter
@NoArgsConstructor
@Table(name = "products")
public class Product
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int price;
private int stock;
public Product(String name, int price, int stock) {
this.name = name;
this.price = price;
this.stock = stock;
}
public void update(String name, int price, int stock) {
this.name = name;
this.price = price;
this.stock = stock;
}
public void decreaseStock(int quantity) {
if (this.stock < quantity) {
throw new IllegalArgumentException("재고가 부족합니다.");
}
this.stock -= quantity;
}
}
코드 설명
import jakarta.persistence.*;
JPA import. (@Entity, @Id, @ManyToOne 포함)
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
lombok import -> 반복 코드 자동화
@Entity
Entity 선언.
@Table(name = "products")
DB 테이블 Table 이름 선언 (매핑)
@Id
PK(기본키) 선언
@GeneratedValue(strategy = GenerationType.IDENTITY)
ID 자동 증가
@ManyToOne(fetch = FetchType.LAZY)
ManyToOne : 연관 관계 매핑 (여러 주문은 하나의 상품을 참조)
fetch - FetchType.Lazy : fetch 타입 선언 (성능 최적화)
@JoinColumn(name = "product_id")
테이블 JOIN 설정
'Spring > - [시리즈] 간단한 CRUD 구현하기' 카테고리의 다른 글
| CRUD 구현 6 - Service 구현 (0) | 2026.05.15 |
|---|---|
| CRUD 구현 5 - DTO (Data Transfer Object) 구현 (0) | 2026.05.15 |
| CRUD 구현 4 - Repository 구현 (0) | 2026.05.14 |
| CRUD 구현 2 - DB 세팅 및 ERD (mySql, JPA) (0) | 2026.05.12 |
| CRUD 구현 1 - 요구 사항 및 개발 환경 (0) | 2026.05.12 |