Bug 220 : M2M cascade save ... violates foreign key constraint
Priority 
High
Reported Version 
 
Logged By 
Rob
Status 
Fixed
Fixed Version 
2.4.0
Assigned To 
 
Product 
Ebean - core
Duplicate Of 
 
Created 
21/02/2010
Updated 
21/02/2010
Type 
Bug
 
Attachments 
No attachments

user = Ebean.find(User.class, 1462);
Role role1 = new Role();
role1.setName("role1");
Ebean.save(role1);
Role role2 = new Role();
role2.setName("role2");
//Ebean.save(role2); // uncomment this and it works
user.getValidRoles().add(role1);
user.getValidRoles().add(role2);
Ebean.save(user);

it crashes on the last line with the exception:

javax.persistence.PersistenceException:
org.postgresql.util.PSQLException: ERROR: insert or update on table
"userroles" violates foreign key constraint "userroles_roleid_fk"
Detail: Key (roleid)=(1463) is not present in table "roles".

(userroles is my m-t-m join table for Users.validRoles)
Here is the relevant logging:

trans[1006], 20:18:20.198, select u.userid as c0 from public.users u
where u.userid = ?
trans[1006], 20:18:20.206, FindById exeMicros[7293] rows[1] type[User]
bind[1462]
trans[1007], 20:18:20.208, insert into public.roles (roleid, name)
values (?, ?)
trans[1007], 20:18:20.208, Binding Insert [public.roles] set[id=1462,
name=role1, ]
trans[1007], 20:18:20.209, Inserted [Role] [1462]
trans[1008], 20:18:20.219, select u.userid as c0 , uv.roleid
as c1, uv.name as c2 from public.users u left outer join userroles
uvz_ on uvz_.userid = u.userid left outer join public.roles uv on
uv.roleid = uvz_.roleid where u.userid = ? order by u.userid
trans[1008], 20:18:20.221, FindMany exeMicros[1835] rows[1:1]
type[User] name[] predicates[u.userid = ? ] bind[1462]
trans[1009], 20:18:20.222, insert into public.roles (roleid, name)
values (?, ?)
trans[1009], 20:18:20.222, Binding Insert [public.roles] set[id=1463,
name=role2, ]
trans[1009], 20:18:20.223, Inserted [Role] [1463]
trans[1009], 20:18:20.224, insert into userroles (userid, roleid)
values (?, ?)
trans[1010], 20:18:20.231, InsertSql table[userroles] rows[1]
bind[1462, 1462, ]
trans[1009], 20:18:20.233, insert into userroles (userid, roleid)
values (?, ?)

 
Rob 21 Feb 08:57
insert into intersection in a different transaction ...

The insert in the middle is using trans[1010] and not [1009] ... and this is a BUG !!

I have a strong suspicion that is the issue here. I'll have to reproduce to confirm and fix.Note the insert/delete into the intersection table actually uses SqlUpdate internally ... looks like the current transaction is not being picked up for the internal use of SqlUpdate.

... so that's a bummer :( ... but your thinking is right on!!

Rob 21 Feb 08:59
Fixed in HEAD

Fixed in HEAD.

woResponse

Upload a file