dont work directly off the mapping tables

21 views
Skip to first unread message

Gianna Giavelli

unread,
Jan 23, 2015, 2:45:53 AM1/23/15
to activejd...@googlegroups.com
I had to re-read the many-many associations docs again before it finally sunk in, don't work directly against the mapping tables. 

Before I was doing Mtbl.findFirst (""Type1ID=? and Type2ID=?", id1, id2) 
then trying to do a delete. 

instead you load both objects fully using 
   Type1 oType1Instance =  Type1.findById(id1);
   Type2 oType2Instance =  Type2.findById(id2); 

then do the add or remove from the mapping table via:
   oType1Instance.add (oType2Instance)

   oType1Instance.remove (oType2Instance)

I'm not sure why I was confused. I think because the pattern to fully load BOTH instance objects when you have the IDs seems a bit unnatural for me. I will try this way. 

I hope this helps people who are slow like me ;*>
   

Gianna Giavelli

unread,
Jan 23, 2015, 3:09:09 AM1/23/15
to activejd...@googlegroups.com
Well I had to use the @many2many to get my mapping table to register. but then it was fine. 

Igor, it was a bit confusing with "sourceFKName" and "targetFKName" I think they would be more easy to understand if they were "sourceColName" "targetColName"

In my table design there is a table Category with ID  and User with ID
I then have 

MTBL_USER_CATEGORY
USERID  INT,
CATEGORYID INT

This is a very common pattern of use.

and the @many2many ends up looking like this....

@Table("category")
@Many2Many(other = User.class, join = "mtbl_user_category", sourceFKName = "categoryid", targetFKName = "userid")
public class Category extends Model
  static 
  {
  }
}

Igor Polevoy

unread,
Jan 25, 2015, 1:07:30 PM1/25/15
to activejd...@googlegroups.com
well, the FK is more appropriate than  Column. The FK might not be physical - that is you do not need a foreign key constraint specified on the DB.

sourceFKName is more appropriate than sourceColName, since it is clearly indicating that the vale corresponds to an ID in another table. 

tx

Gianna Giavelli

unread,
Feb 10, 2015, 6:32:56 PM2/10/15
to activejd...@googlegroups.com
  I wanted to add (to help other users I know you know this Igor) that my solution was NOT to work directly with a mapping table as a MODEL class in your models folder. If you need to do that, its probably best to ad an ID column to it. Instead, the approach is simply keep your table hidden and activejdbc figures it out. Just lookup each item by ID and use add or remove operators. Not 100% optimal efficiency to re-lookup an object by ID but it works fine. So here I am removing a user from a category subscription:

        Category oCategory = Category.findById(strCatId);
    User     oUser     = User.findById(strUserId);
    if (oCategory == null || oUser == null)
    System.out.println ("nulls!");
    else
     oCategory.remove(oUser); 
Reply all
Reply to author
Forward
0 new messages