Automatic id generation

后端 未结 3 537
我寻月下人不归
我寻月下人不归 2021-01-15 11:28

Any one have idea how to generate id starting from 1 so that the next object has 2 and so on?

I have trying the following but dose not work:

<         


        
3条回答
  •  时光说笑
    2021-01-15 11:49

    Beware, using a static variable to keep track of your counter works in a very limited circumstance.

    You can't run this code on more than one machine e.g. a web cluster if it's a web application. Also, the static variable is transient and will reset when you restart your application.

    A common solution to generating a sequential id is to use a database. Most databases have a built-in way do this. For example, IDENTITY in SQL Server or AUTO_INCREMENT in MySQL.

    Consider using a persistence framework like Hibernate and you can declare one of many proven strategies like identity, hilo or uuid some of which are sequential and some aren't. Some are generated by the application and some by the database but the trade-offs are well documented and you'll know what you're getting yourself into.

提交回复
热议问题