So sánh sự khác nhau giữa @ElementCollection và @OneTomany
So sánh @ElementCollection và @OneTomany
- Annotation
@ElementCollectionvà@OneToManyđều dùng cho trường hợp mối quan hệ giữa các bảng là One To Many. - Với annotation
@ElementCollectionthì khi mapping entity trong class Java, ta không cần phải tạo class mapping cho phía many (phía many sẽ là kiểu dữ liệu basic hoặc là 1 class được đánh dấu@Embeddable) - Với annotation
@OneToManythì khi mapping entity trong class Java ta cần phải tạo cả 2 class mapping tới 2 table tương ứng cho cả phía one và phía many. - Annotation
@ElementCollectiondùng cho những trường hợp mà bên phía table many không được dùng 1 cách riêng biệt (chỉ có ý nghĩa khi gán với table phía one). Hoặc những trường hợp phía many chỉ có dữ liệu basic như int, string, …
Ví dụ:
Mối quan hệ giữa table employee và table employee_position là 1 nhiều (1 nhân viên có thể giữ nhiều chức vụ khác nhau)
Nếu mapping theo kiểu @OneToMany thì ta cần phải tạo class Mapping cho cả table employee và table employee_position
@Entity
@Table(name = "employee")
public class Employee {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "employee")
private Set<Position> positions = new HashSet<>();
//...
}
@Entity
@Table(name = "employee_position")
public class Position {
@Column(name = "name")
private String name;
//...
}
Còn với @ElementCollection thì đơn giản hơn nhiều:
@Entity
@Table(name = "employee")
public class Employee {
@Column(name = "position")
@ElementCollection
@JoinTable(name = "employee_position", joinColumns = @JoinColumn(name = "employee_id"))
private List<String> positions;
//...
}
(Xem thêm: Code ví dụ Hibernate One To Many (@OneToMany, @ManyToOne))
(Xem thêm: Code ví dụ Hibernate @ElementCollection )
Okay, Done!
References:
