Skip to content

Commit

Permalink
Add jpa/Entity LifeCycle
Browse files Browse the repository at this point in the history
- JPA μ—”ν‹°ν‹°μ˜ 생λͺ…주기와 μ „ν™˜ 방법
  • Loading branch information
hyh1016 committed Mar 5, 2024
1 parent 823b793 commit 37d4962
Showing 1 changed file with 91 additions and 0 deletions.
91 changes: 91 additions & 0 deletions java/jpa/JPA_Entity_LifeCycle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# JPA Entity의 생λͺ…μ£ΌκΈ°

## Entityλž€?

- 데이터λ₯Ό ν‘œν˜„ν•˜λŠ” POJO
- μ—”ν‹°ν‹° ν΄λž˜μŠ€λŠ” λ°μ΄ν„°λ² μ΄μŠ€μ˜ ν…Œμ΄λΈ”κ³Ό 맀핑됨
- μ—”ν‹°ν‹° μΈμŠ€ν„΄μŠ€λŠ” ν…Œμ΄λΈ”μ˜ ν•˜λ‚˜μ˜ row와 맀핑됨
- μ—”ν‹°ν‹° λ‚΄ ν•„λ“œλŠ” ν…Œμ΄λΈ”μ˜ ν•˜λ‚˜μ˜ columnκ³Ό 맀핑됨

## Entity의 μƒνƒœ

### λΉ„μ˜μ† (new/transient)

- κ°μ²΄λŠ” μžˆμ§€λ§Œ, μ˜μ†μ„± μ»¨ν…μŠ€νŠΈμ— μ €μž₯된 적이 μ—†λŠ” μƒνƒœ

### μ˜μ† (managed)

- μ˜μ†μ„± μ»¨ν…μŠ€νŠΈμ— μ €μž₯된 μƒνƒœ
- μ˜μ†μ„± μ»¨ν…μŠ€νŠΈμ˜ 관리λ₯Ό λ°›μŒ
- 1μ°¨ μΊμ‹œ
- Dirty Checking
- Lazy Loading

### μ€€μ˜μ† (detached)

- μ˜μ†μ„± μ»¨ν…μŠ€νŠΈμ— μ €μž₯λ˜μ—ˆλ‹€κ°€ λΆ„λ¦¬λœ μƒνƒœ
- detach에 μ˜ν•œ κ°œλ³„ 뢄리 λ˜λŠ” μ˜μ†μ„± μ»¨ν…μŠ€νŠΈμ˜ μ™„μ „ν•œ μ΄ˆκΈ°ν™”(clear) λ˜λŠ” μ’…λ£Œ(close)에 μ˜ν•΄ μ˜μ† μƒνƒœμ˜ μ—”ν‹°ν‹°κ°€ μ€€μ˜μ† μƒνƒœλ‘œ μ „ν™˜λ˜κ²Œ 됨

### μ‚­μ œ (removed)

- λ°μ΄ν„°λ² μ΄μŠ€μ—μ„œμ˜ μ‚­μ œκ°€ μš”μ²­λœ μƒνƒœ
- 컀밋 μˆ˜ν–‰ μ‹œ ν•΄λ‹Ή 엔티티와 λ§€ν•‘λ˜λŠ” rowκ°€ 제거됨

## Entity의 μƒνƒœ μ „ν™˜

### λΉ„μ˜μ† β†’ μ˜μ†

```java
public void persist(Object entity);
```

- persistλŠ” λΉ„μ˜μ† μƒνƒœ μ—”ν‹°ν‹°μ˜ μ˜μ†ν™”λ₯Ό μˆ˜ν–‰ν•˜λ©°, λΉ„μ˜μ† μƒνƒœ μ—”ν‹°ν‹°λ§Œ μ²˜λ¦¬ν•  수 있음
- μ€€μ˜μ†/μ˜μ† μƒνƒœμ˜ μ—”ν‹°ν‹°κ°€ 인자둜 주어지면 `EntityExistsException`을 던짐

### λΉ„μ˜μ†/μ€€μ˜μ† β†’ μ˜μ†

```java
public <T> T merge(T entity);
```

- mergeλŠ” 주어진 μ—”ν‹°ν‹°λ₯Ό μ˜μ†μ„± μ»¨ν…μŠ€νŠΈμ— 등둝함
- λΉ„μ˜μ†μ΄λ“ , μ€€μ˜μ†μ΄λ“ , 심지어 μ˜μ† μƒνƒœλ“  λͺ¨λ‘ 처리 κ°€λŠ₯

### μ˜μ† β†’ μ€€μ˜μ†

```java
public void detach(Object entity);
```

- μ˜μ†μ„± μ»¨ν…μŠ€νŠΈλ‘œλΆ€ν„° μ—”ν‹°ν‹°λ₯Ό 제거

### μ˜μ† β†’ μ‚­μ œ

```java
public void remove(Object entity);
```

- μ˜μ† μ—”ν‹°ν‹°λ₯Ό μ‚­μ œ (DBλ‘œλΆ€ν„° 제거)
- μ˜μ† μƒνƒœ μ—”ν‹°ν‹°λ§Œ 처리 κ°€λŠ₯
- μ˜μ†μ„± μ»¨ν…μŠ€νŠΈμ— μ—†λŠ” μ—”ν‹°ν‹°(μ€€μ˜μ†/λΉ„μ˜μ†)κ°€ 주어지면 `IllegalArgumentException`을 던짐

## Spring Data JPA의 save

```java
@Transactional
@Override
public <S extends T> S save(S entity) {

Assert.notNull(entity, "Entity must not be null");

if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
```

- isNew(entity)κ°€ 참이면 λΉ„μ˜μ† μƒνƒœλΌλŠ” λœ»μ΄λ―€λ‘œ persist둜 μ˜μ†ν™”
- 그렇지 μ•Šλ‹€λ©΄ μ€€μ˜μ† λ˜λŠ” μ˜μ† μƒνƒœμΌ κ²ƒμ΄λ―€λ‘œ merge둜 μ˜μ†ν™”

0 comments on commit 37d4962

Please sign in to comment.