You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@cayenne.apache.org by "Daniel Kvasnička jr." <da...@gmail.com> on 2008/01/07 14:06:40 UTC

Changing relationships using only PK

Hi people,
I would like to add an object to a M:N relationship. Cayenne generated
those convenience methods starting with "addTo". These take DataObject
as a parameter and I noticed that it has to be a context-registered
object -- correct?

So if I have a collection of primary keys that correspond to primary
keys of objects I want to add to the relationship, I need to fetch
those objects for those PKs and then add them to the relationship --
correct?
Is it possible to add a object only on the basis of it's PK? Or do I
need to fetch the data first to ensure the object I want to bind is
still valid?

I know I could always do these things with raw sql, but I wanted to
know if there is any object way to do this.

I'm probably only missing something, so thanks for every hint ;)

Dan

-- 
http://www.danielkvasnicka.net -- webdesign & corporate design,
programování internetových a intranetových aplikací

Re: Changing relationships using only PK

Posted by Andrus Adamchik <an...@objectstyle.org>.
Hi Dan,

On Jan 7, 2008, at 3:06 PM, Daniel Kvasnička jr. wrote:

> Hi people,
> I would like to add an object to a M:N relationship. Cayenne generated
> those convenience methods starting with "addTo". These take DataObject
> as a parameter and I noticed that it has to be a context-registered
> object -- correct?

Correct.

> So if I have a collection of primary keys that correspond to primary
> keys of objects I want to add to the relationship, I need to fetch
> those objects for those PKs and then add them to the relationship --
> correct?
> Is it possible to add a object only on the basis of it's PK? Or do I
> need to fetch the data first to ensure the object I want to bind is
> still valid?

You can create a fault for an object without doing a DB fetch (if you  
are absolutely sure that each PK is valid):

   int pk;
   ObjectId id = new ObjectId("MyEntity", "PK_COLUMN", pk);
   Object o = context.localObject(id, null);  // no query will happen  
here

But since Cayenne sets up a reverse relationship, the object will be  
resolved once you add it to the relationship:

   Object m;
   m.addToSomeRelationship(o); // a query will be run here to connect  
"o" back to "m"

So you might just resolve all your objects yourself anyways (at least  
you can batch that operation to make it efficient).

Andrus