views:

1390

answers:

1

I have the following scenario:

I have a system full of users. There is a desire to run contests for users who log into the site over a week or so. Therefore I needed to create a new Contest object which would contain both the entries and the winners.

I created something like this:

private Set<User>;

@OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) 
@JoinTable(name="contest_entries", 
        joinColumns = {@JoinColumn(name = "contest_fk", referencedColumnName="contest_id")},
        inverseJoinColumns = {@JoinColumn(name = "user_fk", referencedColumnName="id")})   
public Set<User> getEntries() {
    return entries;
}

The idea being that a Contest can have multiple entries. Seems simple. It generates the following:

create table contest (contest_id numeric(19,0) identity not null, primary key (contest_id));
create table contest_entries (contest_fk numeric(19,0) not null, user_fk numeric(19,0) not null, primary key (contest_fk, user_fk));
alter table contest_entries add constraint FK7FBD0C65C4F120C2 foreign key (contest_fk) references contest;
alter table contest_entries add constraint FK7FBD0C656ABC75E3 foreign key (user_fk) references user_profile;

However, once a contest is over, the desire is to run another contest. When I attempt to create a new contest and have one of users who had entered previously enter again, I get a unique key constraint. Looking at the table DDL, it makes sense that it does.

So, in essence, I can't run two contests at the same time. I would also lose history of people entering the contests. That's not going to work. I need to be able to run two contests at once with the same users in different contests.

I'm new to JPA, so I have to believe I'm missing something obvious. The system already has a user table and it's populated full of users. There is a desire not to change that table structure. Any ideas on how to solve this? If it matters, the persistence implementation is Hibernate.

+1  A: 

You actualy have a many-to-many relationship. So you should use the @ManyToMany annotation.

Kees de Kooter
When I updated to @ManyToMany, I saw no difference in the DDL created! but I will try it to see if it works.
Mike Cornell
I don't know what it did differently, but there must have been one less constraint added as it worked.Thanks
Mike Cornell