Skip to content
Advertisement

Hibernate / JPA many to many relationship through a join table and a composite key, Unique Constraint issue

So I asked this question yesterday, but the goal posts have changed and the question is different:

Hibernate / JPA Collection of Elements with Many to Many relationship?

I want to know if it’s possible to create entities that will model my required relationship so that Hibernate will create my schema when I fire up my application.

The relationship I want looks like this:

1 http://a8.sphotos.ak.fbcdn.net/hphotos-ak-ash4/417593_10150594114269218_505554217_8657377_1475865815_n.jpg

The thing is that the Join table can actually contain rows that don’t link to any Elements. The structure represents categorising of elements based on the “type” and “value” pair and are entered in to the system outside of this particular application.

What I would like to be able to do is set my Element Hibernate Entity to contain a list of Categories, via a mapping, so that I can actually see what Categories my element belongs to AND so that hibernate creates the table for me.

Here’s what I’ve got so far:mapping this in my Element Entity class like this:

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "ELEMENT_ELEMENTCATOGORY", joinColumns = {
        @JoinColumn(name = "type", referencedColumnName = "type"),
        @JoinColumn(name = "value", referencedColumnName = "value") })
@Column(name = "category")
public List<ElementCategory> getCategories() {
    return categories;
}

This does most of what I want, it creates my tables as above, exactly how I want them bar one thing, there’s a Unique Constraint added in to the Element Table on the (type,value) pair. I don’t want this because multiple elements can have the same type and value pair, I need to be able to stop the Unique Constraint from begin created, but can’t figure out how with the current mapping, can I do this? Am I missing the point of a Many to Many relationship?

Advertisement

Answer

It actually seems quite logical that Hibernate puts a unique constraint on the type and value column.

You say in the @ManyToMany mapping that in the jointable the joincolumns are the type and value column. So basically you say that hibernate should determine which element is coupled to the ElementCategory by the value and type property. therefore the combination ofthose 2 properties should be unique. Otherwise hibernate would not know which Element belong to what ElementType

If you want that multiple Element entities can be coupled to multiple ElementType Entities and the combination of type and value is not always unique, then you can’t use those properties as joincolumns

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement