카테고리 없음
자바 ORM 표준 JPA 프로그래밍 실전 예제 4. 상속관계 매핑
정현3
2022. 5. 29. 14:12
요구사항 추가
- Item의 종류는 Album,Book,Movie가 있고 이후에 더 '확장'될 수 있다
- 모든 데이터는 '등록일'과 '수정일'이 필수다

@Entity
@Inheritance( strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn( name = "DTYPE")
public abstract class Item extends BaseEntity{
@Id
@GeneratedValue
@Column(name = "ITEM_ID")
private Long id;
private String name;
private int price;
private int stockQuantity;
@ManyToMany(mappedBy = "items")
private List<Category> categories = new ArrayList<>();
@Entity
public class Album extends Item{
private String artist;
@Entity
public class Book extends Item{
private String author;
private String isbn;
@Entity
public class Movie extends Item {
private String director;
private String actor;
}
@MappedSuperclass
public class BaseEntity {
private String createdBy;
private LocalDate createdDate;
private String lastModifiedBy;
private LocalDateTime lastModifiedDate;
public class JpaMain {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
try {
Book book = new Book();
book.setName("JPA");
book.setAuthor("김영한");
em.persist(book); //Item테이블에 저장된다
tx.commit();
} catch (Exception e) {
tx.rollback();
} finally {
em.close();
}
emf.close();
}
}