Re: Setting an attribute based on PK?

Ashley Aitken <[email protected]> Thu, 13 May 2004 21:18:33 +0800
Newsgroups gmane.comp.web.webobjects.eof
Message-ID <[email protected]>
Hi Mark,

Thanks for your post.

On 13/05/2004, at 7:19 PM, Mark Ritchie wrote:

> On 25-Apr-04, at 9:07 AM, Ashley Aitken wrote:
>> Just saw some code on WODev (thanks to all who have created that 
>> wonderful resource) for generating primary keys on insert.  I will 
>> try that and see how it goes.
>>
>> Of  course, the downside is that the primary keys may not get used 
>> (ie no saveChanges) and you lose any sequencing/counting on the 
>> primary key (but then it is supposed to be database-specific not 
>> app-specific).
> ...
>
> One approach might be to initiate some custom code just before you 
> call saveChanges.
> That code would:
> 1) initiate PK generation manually and assign the PK
> 2) determine if value(s) need to be derived from the PK and set the 
> value(s)
> 3) initiate the saveChanges
>
> This approach has the benefits:
> a) changes to the EO are all made prior to the call to saveChanges  
> (what EOF expects.)
> b) there's no need to guess when the PK generation occurs during the 
> saveChanges
> c) if you hold off generating the PK until the user has initiated the 
> save then you have
> much less chance of the PK not getting used.  This avoids gaps in the 
> PK's due to the
> user deciding to not save an EO which has been partially created.
>
> Note: It's perfectly legal to set the PK manually prior to 
> saveChanges. EOF will use the
> value which you've assigned and it's easy for you if you ask EOF to 
> give you the next
> available PK for that entity. (see EOAdaptorChannel - 
> primaryKeysForNewRowsWithEntity)

That sounds like the best solution (well thought out and all above 
board).  I guess one could setup a method for an EO subclass, something 
like generatePrimaryKey(), that would do as you suggest and would be 
called for new EOs before saveChanges.  EOs that want to use this value 
to derive attributes could subclass this method, call super and then do 
what they want.

If one was using D2W(onder), as I am, one would probably have to 
subclass the EC and override saveChanges, to be able to call this 
method for all newly inserted EOs before calling super.saveChanges().  
I think that would work.

As I think the thread showed, I had problems (with D2W) when I tried to 
set generate the primary key in awakeOnInsert, and problems when I 
tried to set the attributes during the saveChanges.  I eventually gave 
up on using the PK and made my own "sequence table" with an entry for 
each EO (that requires sequenced attributes) and increment the values 
therein (like WO does for it's PK generation).

It works ok  but I'll keep your solution in mind for next time.

Thanks,
Ashley.

--
Ashley Aitken
Perth, Western Australia
mrhatken at mac dot com