๋ฐ์ํ
์๋ฐ ORM ํ์ค JPA ํ๋ก๊ทธ๋๋ฐ - ๊ธฐ๋ณธํธ์ ๊ณต๋ถํ๋ฉฐ ์ ๋ฆฌํ ๋ด์ฉ์ ๋๋ค.
๐ @MappedSuperclass
- ๊ณตํต ๋งคํ ์ ๋ณด๊ฐ ํ์ํ ๋ ์ฌ์ฉํ๋ค!
- ์์๊ด๊ณ ๋งคํ X
- ์ํฐํฐ X, ํ ์ด๋ธ๊ณผ ๋งคํ X
- ๋ถ๋ชจ ํด๋์ค๋ฅผ ์์ ๋ฐ๋ ์์ ํด๋์ค์ ๋งคํ ์ ๋ณด๋ง ์ ๊ณตํ๋ค.
- ์กฐํ, ๊ฒ์ ๋ถ๊ฐ (em.find(BaseEntity) ๋ถ๊ฐ!)
- ์ง์ ์์ฑํด์ ์ฌ์ฉํ ์ผ์ด ์์ผ๋ฏ๋ก ์ถ์ (abstract) ํด๋์ค ๊ถ์ฅ
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;
/**
* @MappedSuperclass : ๊ณตํต์ ๋งคํ ์ ๋ณด๊ฐ ํ์ํ ๋
* ๋ด๊ฐ ์ํ๋ ํ
์ด๋ธ์ ๋๊ฐ ์์ฑํ๊ณ (createdBy), ์ธ์ ์์ฑํ๋์ง(createdByDate), ๋ฑ๋ฑ
* ์ถ๊ฐ ํ๊ณ ์ถ์๋, ๊ท์ฐฎ์์ ๋์ด์ฃผ๋ ์ ๋
ธํ
์ด์
์ด๋ค.
*
* (*) ์ด ํด๋์ค๋ ์์ฑํด์ ์ฌ์ฉํ ์ผ์ด ์์ผ๋ฏ๋ก ์ถ์ํด๋์ค๋ก ์ ์ธ!!
*
* ๋ฐฉ๋ฒ. BaseEntity๋ผ๋ ํด๋์ค๋ฅผ ์์ฑํด์ ์ถ๊ฐํ๊ณ ์ถ์ ์ ๋ณด๋ค์ ๋ฃ๊ณ , @MappedSuperclass ๋ง ๋ถ์ฌ์ฃผ๋ฉด ๋!
* ๊ทธ๋ฆฌ๊ณ ์ถ๊ฐ ํ๊ณ ์ถ์ ์ํฐํฐ์ ์์์ ์์ผ์ฃผ๋ฉด ๋๋ค.
* ์) Book ์ ์ถ๊ฐํ๊ณ ์ถ๋ค -> public class Book extends BaseEntity ..
*/
@MappedSuperclass
public abstract class BaseEntity {
private String createdBy;
private LocalDateTime createdByDate;
private String lastModifiedBy;
private LocalDateTime lastModifiedDate;
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public LocalDateTime getCreatedByDate() {
return createdByDate;
}
public void setCreatedByDate(LocalDateTime createdByDate) {
this.createdByDate = createdByDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public LocalDateTime getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(LocalDateTime lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}
@Entity
public abstract class Item extends BaseEntity {
@Id @GeneratedValue
private Long id;
private String name;
private int price;
// getter, setter ์๋ต
}
public class JpaMain {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("chapter7"); //persistenceName : resource/META-INF/persistence.xml ํ์ผ์ ์ค์ ํ name
EntityManager em = emf.createEntityManager();
// code
EntityTransaction tx = em.getTransaction();
tx.begin();
try {
Book book = new Book();
book.setName("book1");
book.setCreatedBy("set1");
book.setCreatedByDate(LocalDateTime.now());
em.persist(book);
em.flush();
em.clear();
Book findBook = em.find(Book.class, book.getId());
String createdBy = findBook.getCreatedBy();
LocalDateTime createdByDate = findBook.getCreatedByDate();
System.out.println(createdBy + ", " + createdByDate);
tx.commit(); // ์ด๋ ์์๋๋ ์ฟผ๋ฆฌ๋ฅผ ํ๋ฐฉ์ ๋ ๋ฆฐ๋ค.
} catch (Exception e) {
tx.rollback();
} finally {
em.close();
}
emf.close(); // ํญ์ ๊ผญ ๋ง์ง๋ง์ ๋ซ์์ค์ผํจ!
}
}
์ด๋ ๊ฒ ๋๋ฉด Item์ ํ์ฅํ๊ณ ์๋ Book ํด๋์ค์๋ ๊ณตํต ๋งคํ ์ ๋ณด๊ฐ ์๊ธฐ๊ฒ ๋๋ค.
๊ทธ๋์ book.setCreateBy() ๋ฅผ ํธ์ถํ ์ ์๊ฒ ๋๋ค.
๋ฐ์ํ