# 關於@ElementCollection如何使用?
###### tags: `Hibernate`
可以使用@ElementCollection取存一個list的value作為一個entity屬性,但是不需要去model一個額外的entity。但其實不推薦使用,如果可以還是透過reference最好。
下面有個範例,一個Author entity使用一個elementCollection標籤去map一個list of phone numbers to the phoneNumbers attributes.
> Author.java
```java
@Entity
public class Author{
@ElementCollection
private List<String> phoneNumbers = new ArrayList<String>();
...
}
```
> Question: 今天你想要透過phoneNumber去找到Author
- 在你reference where clause說你想要透過`where phoneNumber = :phoneNumber`來找到Author之前, 你需要Author的entity裡面的phoneNumbers element 使用Join之後才可以做到。
```java
TypedQuery<Author> q = entitymanager.createQuery("SELECT a FROM Author a JOIN a.phoneNumbers p WHERE p = :phoneNumber");
q.setParameter("phoneNumber", "123456");
Author a = q.getSingleResult();
```
==Question: Join? Left Join? Right Join==https://hackmd.io/@EasyEatWeb/H1MaII3HP
# ElementCollection到底是甚麼?
其實它就只是一個功能說如果你想要取得某個欄位的值,這個欄位是來自於別的table,可是你他媽又不想要設那個table的關聯...,那這個就可以符合你的需求。我覺得可能這樣的情況下都是你懶得改code或是懶得去連接
# ElementCollection 跟 OneToMany到底有甚麼差別?
其實很簡單,elementcollection就是專門for mapping non-entities的!! 然後oneToMany就是專門map entities
別人的說法:
- ElementCollection is a standard JPA annotation, which is now preferred over the proprietary Hibernate annotation CollectionOfElements.It means that the collection is not a collection of entities, but a collection of simple types (Strings, etc.) or a collection of embeddable elements (class annotated with @Embeddable).It also means that the elements are completely owned by the containing entities: they're modified when the entity is modified, deleted when the entity is deleted, etc. They can't have their own lifecycle.
[參考](https://stackoverflow.com/questions/8969059/difference-between-onetomany-and-elementcollection)