views:

25

answers:

2

I have defined a collection in Hibernate like this:

...
public class Item {
    ...
    @ElementCollection
    List<Object> relatedObjects;
}

It creates a mapping table with colums item_id and object_id.

The problem is that object_id seems to be unique. In other words I can not have two different items being related to the same object. But that is what I want.

I would like the combination of item_id and object_id to be unique. How do I do that?

A: 

Perhaps I need to use a ManyToMany mapping.

Rickard Lindberg
A: 

That's not what I'm experiencing. For the following entity:

@Entity
public class Person implements Serializable {
    @Id
    @GeneratedValue
    private Integer id;
    private String firstName;
    private String lastName;
    @Enumerated(EnumType.STRING)
    private Gender gender;

    @ElementCollection
    private Set<String> nicknames = new HashSet<String>();

    private String dept;

    // getters, setters
}

The following tables get created:

create table Person (id integer generated by default as identity, dept varchar(255), firstName varchar(255), gender varchar(255), lastName varchar(255), primary key (id))
create table Person_nicknames (Person_id integer not null, nicknames varchar(255))
alter table Person_nicknames add constraint FK24F0D97B19ACB65E foreign key (Person_id) references Person

There is no unique constraint. But I can't say more without seeing your "Object" class (it's an embeddable class, right?).

PS: ElementCollection can't be a ManyToMany, this is more a OneToMany.

Pascal Thivent