I am having a problem with mapping a entity that contains a list (or map). I’ve tried various combinations of annotations but the two variations that work the ‘best’ both have this behavior. If the parent-object has, for example, 3 child objects, the parent object is retrieved three times.
My Code
In my case i have an UserOrder object that contains pairs of Products with a count. The datastructure looks like this
@Entity
public class UserOrder{
/*
* VARIATION 1
* I did actually vary some of these annotions, not all are necessary.
* I believe the @CollectionTable is the key here
*/
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable
@Column
@Embedded
private List<ProductCount> products;
/*
* VARIATION 2
*/
@ElementCollection(fetch = FetchType.EAGER)
private Map<Product, Integer> products = new HashMap<Product, Integer>();
// get/set
// ...
}
@Embeddable
/* Only used in variation 1 */
public class ProductCount{
@OneToOne
private Product product;
@Column
private Integer amount;
// get/set
}
@Entity
public class Product
{
// ...
}
Then this is called and displayed using something like this (this is for variation 2)
<!-- Called via DAO/Service layers
List<Order> orders = getSession().createCriteria(UserOrder.class).list();
-->
<c:forEach items="${orders}" var="order">
<fmt:formatDate value="${order.time}" type="both" />
<c:forEach items="${order.products}" var="pc">
${pc.value} x ${pc.key.name}
</c:forEach>
</c:forEach>
For the record, I am using Spring (3.1), Hibernate (3.5) and I’d like to stay with JPA annotations.
The Problem
When I retrieve the orders, I get a UserOrder-object for each of the products it contains, instead of one UserOrder for each order I have stored. So I get duplicates in my list, all with complete information of the products it contains. Orders without products are also included
- Order 1 — Has 2 products
- 1 x DogToy1
- 3 x Cat Toy 1
- Order 1 — Has 2 products
- 1 x DogToy1
- 3 x Cat Toy 1
- Order 2 — Has 1 product
- 3 x Cat Toy 1
- Order 3 — Has 0 products
How do I make Hibernate return me one (1) UserOrder instead of one-for-each-product? Or, have I even taking the right approach to modelling this structure?
Options: