Skip to content

Instantly share code, notes, and snippets.

@RUBenGAMArrarodRiguEZ-ToMtOm
Last active January 3, 2016 12:39
Show Gist options
  • Save RUBenGAMArrarodRiguEZ-ToMtOm/8464457 to your computer and use it in GitHub Desktop.
Save RUBenGAMArrarodRiguEZ-ToMtOm/8464457 to your computer and use it in GitHub Desktop.
package com.myapp
class Post {
String content
static belongsTo = [user: User]
static constraints = {
}
}
package com.myapp
class User {
String username
static hasMany = [posts: Post]
static constraints = {
}
}
package com.myapp
import org.junit.Test
class UserIntegrationTests {
@Test
public void testDeleteFK() {
def alice = new User(username: 'Alice')
alice.save(failOnError: true)
def post
post = new Post(user: alice, content: 'ketchup & mayo, please')
post.save(failOnError: true)
assert Post.count(), 'Post should have been saved'
// Since this is a test we add flush before continuing to the delete part
alice.save(failOnError: true, flush: true)
def users = User.list()
users.each {
// Flush before continuing to the verification part
it.delete(flush: true) //DataIntegrityViolationException
}
assert !User.count(), 'All users should have been deleted'
assert !Post.count(), 'All post should have been cascade deleted'
}
}
@RUBenGAMArrarodRiguEZ-ToMtOm
Copy link
Author

When the it.delete(flush: true) is executed, I get a foreign key restriction error:

| Failure:  testDeleteFK(com.myapp.UserIntegrationTests)
|  org.springframework.dao.DataIntegrityViolationException: could not delete: [com.myapp.User#1]; SQL [delete from user where id=? and version=?]; constraint ["FK3498A01D042DE0: PUBLIC.POST FOREIGN KEY(USER_ID) REFERENCES PUBLIC.USER(ID)";
SQL statement:
delete from user where id=? and version=? [23503-164]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not delete: [com.myapp.User#1]
        at com.myapp.UserIntegrationTests$_testDeleteFK_closure1.doCall(UserIntegrationTests.groovy:97)
        at com.myapp.UserIntegrationTests.testDeleteFK(UserIntegrationTests.groovy:95)
...
Referential integrity constraint violation: "FK3498A01D042DE0: PUBLIC.POST FOREIGN KEY(USER_ID) REFERENCES PUBLIC.USER(ID)"; SQL statement:delete from user where id=? and version=? [23503-164]

If I replace:

post = new Post(user: alice, content: 'ketchup & mayo, please')
post.save(failOnError: true)

with

post = new Post(content: 'ketchup & mayo, please')
alice.addToPosts(post)

the test passes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment