Hi,
Can anyone help me with a question regarding element collections? I am a bit of a noob having only used Hibernate for a few months, so apologies if I haven't understood this problem properly.
This is a product inventory system. Some products are considered to be 'consumables' for other products.
It returns data in JSON format. As there are many products and relations, I want to keep the payload of data quite low.
So when a product is a consumable, I just want to return a list of product ids it is a consumable for, not the full related product.
On this Product entity, there is a set of 'RelatedProduct'. This embeddable has a single string property called 'relatedId'.
So this element collection of productIds this product is a consumable for works fine:
Code:
@ElementCollection
@CollectionTable(name="tbl_product_consumables", joinColumns={@JoinColumn(name="businessId"),@JoinColumn(name="id")})
@AttributeOverrides({
@AttributeOverride(name="businessId", column=@Column(name="BusinessId", table="tbl_product_consumables")),
@AttributeOverride(name="id", column=@Column(name="Id", table="tbl_product_consumables")),
@AttributeOverride(name="relatedId", column=@Column(name="RelatedId", table="tbl_product_consumables", nullable = false, length = "5"))
})
public Set<RelatedProduct> getIsConsumableFor() {
return isConsumableFor;
}
So it works fine for one direction. But now I want to also get the product ids in the opposite direction too, so that I can find out product Ids that are consumables for this product.
My first thought was to add a second elementcollection, but swapping the columns for the Id and Related Id:
Code:
@ElementCollection
@CollectionTable(name="tbl_product_consumables", joinColumns={@JoinColumn(name="businessId"),@JoinColumn(name="relatedId")})
@AttributeOverrides({
@AttributeOverride(name="businessId", column=@Column(name="BusinessId", table="tbl_product_consumables")),
@AttributeOverride(name="id", column=@Column(name="RelatedId", table="tbl_product_consumables", nullable = false, length = "5")),
@AttributeOverride(name="relatedId", column=@Column(name="Id", table="tbl_product_consumables"))
})
public Set<RelatedProduct> getConsumables() {
return consumables;
}
This does actually work fine for retrieving data.
But I noticed a problem with the primary key.
If I include either one of these element collections on its own, a single primary key is generated containing businessId,Id and relatedId.
But when they are both included, a secondary key is also generated for businessId,Id
This means that I can only insert one record for each product.
I assumed they would attempt to generate and use the same primary key, as it is the same fields?
So can I stop it generating the second key? Or should this be done another way?
Thanks!