일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- html
- oauth
- SseEmitter
- Project
- JPA
- python
- cookie
- Java
- Stream
- programmers
- DI
- Hibernate
- javascript
- web
- real time web
- session
- Spring Security
- 항해99
- spring
- flask
- google oauth
- WIL
- hanghae99
- jQuery
- JWT
- bean
- 생명주기 콜백
- Anolog
- jenkins
- server send event
Archives
- Today
- Total
끄적끄적 코딩일지
[Spring] Entity에서 Collection 사용하기 본문
Java상에서 Collection이란?
여러 데이터들의 집합, 그룹등을 의미하며 List, Map, Set등 모든 데이터들의 집합을 의미하는 클레스들은 모두 Collection을 참조하고 있다.
Entity에서 Collection 사용하기
다른 Entity와 List등의 연관관계는 OneToMany 혹은 ManyToMany를 사용하여 표시할 수 있다.
하지만 만약 단순한 String 값이나 Map<Entity,Integer> 같이 Map으로 묶는 경우에는
해당 객체가 Colletion객체임을 알려주는 @ElementCollection을 사용해야한다.
1. List
@Entity
public class EntityClass{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
....
@ElementCollection
@CollectionTable(
name = "something_simple_list",
joinColumns = {@JoinColumn(name = "something_id", referencedColumnName = "id")}
)
private List<String> something= new ArrayList<>();
public void addSomething(String something){
this.something.add(something);
}
}
테스트 코드
@Autowired
private SomethingRepo somethingRepo;
@Test
void CollectionTest() {
SomethingEntity something = new SomethingEntity();
something.addSomething("this");
something.addSomething("is");
something.addSomething("list");
somethingRepo.save(something);
SomethingEntity something2 = new SomethingEntity();
something2.addSomething("hibernate");
something2.addSomething("공부하기");
something2.addSomething("어렵다");
somethingRepo.save(something2);
}
결과
2. Map - 단순 key, 단순 value
@Entity
public class EntityClass{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
....
@ElementCollection
@CollectionTable(
name = "something_simple_map",
joinColumns = {@JoinColumn(name = "something_id", referencedColumnName = "id")}
)
@MapKeyColumn(name="string_key")
@Column(name="string_value")
private Map<String,String> simpleMap = new HashMap<>();
public void addSomething(String key,String value){
this.simpleMap.put(key,value);
}
}
테스트 코드
@Autowired
private SomethingRepo somethingRepo;
@Test
void CollectionTest() {
SomethingEntity something = new SomethingEntity();
something.addSomething("key1","value1");
something.addSomething("key2","value2");
something.addSomething("key3","value3");
somethingRepo.save(something);
SomethingEntity something2 = new SomethingEntity();
something2.addSomething("키1","값1");
something2.addSomething("키2","값2");
something2.addSomething("키3","값3");
somethingRepo.save(something2);
}
결과(Map이라서 순서가 안지켜짐)
3. Map - Entity key, 단순 value
Entity 객체는 Key 으로만 설정할 수 있다.
@Entity
public class EntityClass{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
....
@ElementCollection
@CollectionTable(
name = "something_another_map",
joinColumns = {@JoinColumn(name = "something_id", referencedColumnName = "id")}
)
@MapKeyJoinColumn(name="another_id")
@Column(name="string_value")
private Map<AnotherEntity,String> entityKeyMap = new HashMap<>();
public void addSomething(AnotherEntity anoter,String value){
this.entityKeyMap.put(anoter,value);
}
}
@Entity
public class AnotherEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
}
테스트 코드
@Autowired
private SomethingRepo somethingRepo;
@Autowired
private AnotherRepo anotherRepo;
@Test
void CollectionTest() {
SomethingEntity something = new SomethingEntity();
AnotherEntity another1 = new AnotherEntity();
AnotherEntity another2 = new AnotherEntity();
anotherRepo.save(another1);
anotherRepo.save(another2);
something.addSomething(another1,"this is another1 value");
something.addSomething(another2,"this is another2 value");
somethingRepo.save(something);
}
결과
@ElementCollection
- 연결된 부모 Entity와 함께 사용된다. (따로 테이블만 선택해서 독립적으로 사용하지 못한다.)
- 항상 부모Entity와 저장되거나 삭제되서 cascade 옵션은 제공하지 않는다.(부모 entity를 save할때 새로 추가된 값은 저장되고 없어진 값은 삭제한다. 그리고 부모 entity가 삭제되면 연관된 모든 데이터도 삭제한다.)
- 부모 Entity Pk 와 추가 Column으로 구성된다.
- 매핑 테이블에는 식별자 개념이 없어서(해당 테이블에는 PK 가 없다) 컬렉션 값 변경 시 전체 삭제 후 새로 추가한다.
@Entity 연관(@OneToMany/ @ManyToMany)
- 다른 Entity에 의해 관리될 수 있다.
- 보통 부모Entity와 자식 Entity PK를 외래키로 연관관계를 맺는다.
'Spring' 카테고리의 다른 글
[Spring] Spring, React 연동하기(CORS,Proxy) (0) | 2022.06.12 |
---|---|
[Spring] SSeEitter 사용하기 (0) | 2022.06.09 |
[Spring] Spring Security + OAuth2 (2) - 코드 구현하기 (0) | 2022.06.08 |
[Spring] Spring Security + OAuth2 (1) - 프로젝트 설정하기 (0) | 2022.06.08 |
[Spring] Spring Security + JWT (0) | 2022.06.08 |