Domain
WishList Entity
import jakarta.persistence.Column;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;
@Entity
@Table(name = "wish_products", uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id", "product_id"})})
public class WishList {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long wishListId;
@Embedded
private UserProduct userProduct;
@Column(nullable = false)
private int quantity;
protected WishList() {
}
public WishList(UserProduct userProduct, int quantity) {
this.wishListId = null;
this.userProduct = userProduct;
this.quantity = quantity;
}
// getter setter 생략
}
UserProduct 객체 (embeddable)
import gift.product.entity.Product;
import jakarta.persistence.Embeddable;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
@Embeddable
public class UserProduct {
private Long userId;
@ManyToOne
@JoinColumn(name = "product_id")
private Product product;
protected UserProduct() {
}
public UserProduct(Long userId, Product product) {
this.userId = userId;
this.product = product;
}
// getter, setter 생략
}
Product Entity (Join Column)
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long productId;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private int price;
@Column(nullable = false)
private String image;
protected Product() {
}
public Product(String name, int price, String image) {
this.productId = null;
this.name = name;
this.price = price;
this.image = image;
}
// getter, setter 생략
}
접근 방법
Sort property
// userProduct 객체의 product 객체의 price 변수에 접근
String sortProperty = "userProduct_product_price";
Direction direction = Direction.fromString("ASC");
Sort sort = Sort.by(direction, sortProperty);
JPA 쿼리 자동 생성
// userProduct라는 객체 내부의 userId라는 변수에 접근
Page<WishList> findByUserProductUserId(Long userId, Pageable pageable);
결론
위의 두 예제 말고도 접근할 방법은 더 많을 수도 있겠습니다.
Table의 column 이름이 아닌 객체 이름을 기준으로 접근하면 "이게 되네"라는 느낌으로 성공할 수 있을 겁니다.
'백엔드 > Spring' 카테고리의 다른 글
[Spring] JpaRepository 쿼리 자동 생성 예제 (1) | 2024.07.13 |
---|