Details
-
Type:
Bug
-
Status:
Open
-
Priority:
Major
-
Resolution: Unresolved
-
Affects Version/s: 1.3.7
-
Fix Version/s: None
-
Component/s: Persistence
-
Environment:Windows 7, Grails 1.3.7, Mysql
Description
I have a class
class Product{
static hasMany = [competitorProducts : Product]
static mapping = {
competitorProducts joinTable:[name:'product_competitor_products', key:'product_id', column:'competitor_product_id']
}
}
Now, lets say I add three competitor products to a product x using x.addToCompetitorProducts, It will insert three records into the product_competitor_products table.
Now, I do x.competitorProducts.clear() and then re-add the same three competitor products to x using x.addToCompetitorProducts
I dont know why, but it creates duplicate records of same competitor products for product x in the table. After calling save, there will be six records in the table, instead of just three. The three records will be duplicate.
Please note - It will work in tests and can not be reproduced in tests, That said
If you do following in tests, it will pass without any issues, It will show you just three competitor products if you debug the running application and inspect product.competitorProducts, but if you check in database, there will be six records and not three.
following test will pass, but if you run app in dev env, and do the same, there will be six records in db.
product.addToCompetitorProducts(p1) product.addToCompetitorProducts(p2) product.addToCompetitorProducts(p3) product.save() product = Product.get(id) assert product.competitorProducts.size() == 3 product.competitorProducts.clear() product.addToCompetitorProducts(p1) product.addToCompetitorProducts(p2) product.addToCompetitorProducts(p3) product.save() product = Product.get(id) assert product.competitorProducts.size() == 3
Note - It works if you add different competitor records rather then the same after doing clear(), and it will create just three records in database, (removing old three records and adding three new)
Please look at these threads
http://grails.1312388.n4.nabble.com/hasMany-JoinTable-issue-does-not-delete-records-from-the-join-table-td3818727.html
http://grails.1312388.n4.nabble.com/Remove-from-collection-td1355730.html
Here's the code that you can use to reproduce the issue.
Execute following code two/three times
As we clear the competitors every time the above code runs, after two/three runs, there should be just two records in the table 'a_competitors'
But there will be duplicate records.