简体   繁体   中英

Should I let NHibernate generate GUIDs for created entities, or is it safe to generate the GUIDs client-side?

I'm trying to improve the responsiveness of an app. The user indicates they want to add a Song object to a Playlist. To do so, I create a new Song object, save it to my server to set its ID, then, when the server responds successfully, I add the Song object to the Playlist.

This has the side-effect of giving the user an awkward delay between their action and the app's response.

I am wondering if it is OK to generate the GUIDs for my entities client-side instead of passing an object with an empty GUID to NHibernate (which then sets it while working with my Sql Server DB.)

I would be using this method to generate a GUID :

'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
    return v.toString(16);
});

I am concerned about collisons, though. Should I be? Or are client-side and server-side generation of GUIDs mostly the same?

When generating IDs on the client side you cannot guarantee unique IDs, because client side javascript code can be modified by versed users (or the request sent to the server can be modified). So you should generate the GUID on the server side to be save.

The method of generating GUID you mentioned is definitely not safe and would result in collisions sooner or later. You should definitely generate GUID on the server side.

Is there any reason for you to create new Song object?
Are you copying existing objects or creating brand new ones?
If it's a copy, you should consider linking the original to the playlist (you don't have to wait for the GUID then).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM