1

Here is the stripped down version of my code:

@Entity
public class Item implements Serializable{

@Id
@GeneratedValue
private long id;

@ElementCollection(fetch=FetchType.EAGER ,targetClass=Cost.class)
@CollectionTable(name="ItemCost", joinColumns = {@JoinColumn(name="itemId")})
private Set<Cost> costs= new HashSet<Cost>();

@ElementCollection(fetch=FetchType.EAGER ,targetClass=ItemLocation.class)
@CollectionTable(name="ItemLocation", joinColumns = {@JoinColumn(name="itemId")})
private Set<ItemLocation> itemLocations;

}

Is the above code allowed? I have two embeddable classes Cost and ItemLocation that I am using with @ElementCollection.

Issue: When I try to run a named query

@NamedQuery(name = "Item.findAll", query = "SELECT i FROM Item i")

I have strange behavior. The records in the second elementcollection (ItemLccation table) are getting doubled (inserted into the table).

Veer Muchandi
  • 267
  • 5
  • 16

1 Answers1

0

What it comes to JPA 2.0, your code is allowed. It is perfectly legal to have more than one collections that are annotated with ElementCollection. Also, it most likely does not have anything to do with problem you have. By the way, to find out is that really your problem, had you tried your code without costs collection?

In which point exactly duplicates in this collection occur first time? If ItemLocation does not define equals&hashcode, duplicates can easily come as result of adding items by yourself.

Possibly you are facing this problem: Primary keys in CollectionTable and chancing type to list and adding @OrderColumn will help.

Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
  • Thanks I tried without adding any data to costs collection and I still have the issue with location. So my problem is not related to multiple element collections. I am getting duplicates when I am trying to query the item. For each find, it is doubling the records in the item location.I did not understand your comment on equals & hashcode. ItemLocation does not have an Id as it is an Embeddable. For Item I am using @GeneratedId – Veer Muchandi Mar 02 '12 at 18:06
  • Adding @OrderColumn has taken care of this issue. I did not understand the suggestion on equals&hashcode though. Can you please explain with an example of what it means for an Embeddable class with no Primary Key? Thanks for your help. – Veer Muchandi Mar 02 '12 at 20:20