I've been using Hibernate for the better half of 10 years now (since Hibernate 2), and while I really like Hibernate it still surprises me from time to time how complex things can get. This post highlights a few of these hurdles. I'm pretty sure other ORMs have the same or similar issues, but I'll use Hibernate here because that's what I know best. To demonstrate things I will use the classic Order/LineItem example:
@Entity
@Table(name = "T_ORDER")
public class Order {
@Id
@GeneratedValue
private Long id;
@ElementCollection
@CollectionTable(name = "T_LINE_ITEM")
private Set<LineItem> lineItems = new HashSet<LineItem>();
public Long getId() {
return id;
}
public Set<LineItem> getLineItems() {
return lineItems;
}
public int getTotalPrice() {
int total = 0;
for (LineItem lineItem : lineItems) {
total += lineItem.getPrice();
}
return total;
}
}
@Embeddable
public class LineItem {
@ManyToOne(fetch = FetchType.LAZY)
private Product product;
private int price;
@SuppressWarnings("unused")
private LineItem() {
}
Read more: ERWIN VERVAET
@Entity
@Table(name = "T_ORDER")
public class Order {
@Id
@GeneratedValue
private Long id;
@ElementCollection
@CollectionTable(name = "T_LINE_ITEM")
private Set<LineItem> lineItems = new HashSet<LineItem>();
public Long getId() {
return id;
}
public Set<LineItem> getLineItems() {
return lineItems;
}
public int getTotalPrice() {
int total = 0;
for (LineItem lineItem : lineItems) {
total += lineItem.getPrice();
}
return total;
}
}
@Embeddable
public class LineItem {
@ManyToOne(fetch = FetchType.LAZY)
private Product product;
private int price;
@SuppressWarnings("unused")
private LineItem() {
}
Read more: ERWIN VERVAET