* After previewing this post 3-4 times and finally submitting it I realized that this is exactly how a OneToMany ought to behave. The obvious solution is to change this to a ManyToMany relation. Thanks, my mistake. Moderators plz delete.
Hello everyone, I'm having some sort of schema generation or MySQL constraint issue. I have the following Project mapping:
Code:
@OneToMany
@JoinTable(
name = "projectAdmins",
joinColumns = { @JoinColumn(name="projectId") },
inverseJoinColumns = { @JoinColumn(name="userId") }
)
private Set<Account> admins = new HashSet<Account>();
Here is the SQL that is generated to create the projectAdmins table:
Code:
create table projectAdmins (projectId integer not null, userId integer not null, primary key (projectId, userId), unique (userId)) ENGINE=InnoDB
alter table projectAdmins add index FK9407277D5DA0C181 (projectId), add constraint FK9407277D5DA0C181 foreign key (projectId) references Project (id)
alter table projectAdmins add index FK9407277D735227DB (userId), add constraint FK9407277D735227DB foreign key (userId) references Account (id)
My failing test case creates two projects, each with its own account (third constructor parameter) and each with a list of admins containing only the first account.
Code:
// persist the first project & account
Account account1 = new Account("account1", "account1", "adf3r23");
Project project1 = new Project("name1", "url1", account1);
project1.getAdmins().add(account1);
projectDao.makePersistent(project1);
simulateNewSession();
Account account2 = new Account("account2", "account2", "f4");
Project project2 = new Project("name2", "url2", account2);
project2.getAdmins().add(account1); // shares an admin with project1
projectDao.makePersistent(project2);
the first project association is projectId=1 & userId=1
the second association is projectId=2 & userId=1 but it throws this exception:
java.sql.BatchUpdateException: Duplicate entry '1' for key 'userId'
Even when I try unique=false on both the @JoinColumn s Hibernate generates the above SQL and the same error occurs. Why is Hibernate making userId unique, isn't primary key (projectId, userId) enough?
Any suggestions would be great appreciated! Thanks!
Hibernate version: 3.2.1.ga
I'm having problems with: MySQL: 5.2.3-falcon-alpha (Windows) and 5.0.24a (Ubuntu). This is not an issue with Hsqldb (probably because it doesn't enforce constraints)
[/b]