cancel
Showing results for 
Search instead for 
Did you mean: 

Autogenerated ID in CAP

balbino_soaresferreirafil
Active Participant

Hi guys, I would like to know the best aproach and recomendation to create a autogenerated ID in a entity.

entity Courses: managed{
key ID: Integer;
name: localized String;
}

I would not like to use UUID, because I want a ID more simple for users identify. Is there a way to create a sequence in definition? Or I need to do this in the custom logic of the service?

View Entire Topic
frasie
Advisor
Advisor

Hi,

I have implemented auto increment id's as follows

  async function getNextId(entity){
    const result = await SELECT.one(entity).orderBy({id: 'desc'})
    return result ? result.id + 1 : 1
  }

  srv.before ('CREATE','Teams', async context => {  
    context.data.id = context.data.id || await getNextId(Teams)
  })

If no id was provided it will simply take the max. id + 1.

Regards,
Frank

avula913
Discoverer
0 Kudos

Hi,

We have implemented service.before handler to generate ID based on the maximum number of a field and implementing by 1 on maxID.

This is working good for the single post request. But when we are trying through the sap UI5 with the batch request it is failing.

When are adding more than 2 entries and saving the entries. It is throwing an error as entry already exists.

Please help me how to handle this use case

frasie
Advisor
Advisor
0 Kudos

Hi Avula,

David Kunz from CAP development recommended to use SELECT.forUpdate() to avoid this race condition. Never tried it myself yet.