JPA, Reuse of deleted ID

江枫思渺然 提交于 2021-02-17 05:22:09

问题


I use an Entity with generated ID (so Entity has a field, that marked by @Id and @GeneratedValue). I'm going to use generated id of the entities in the business logic and I have a question:

If I delete an entity, its ID will be re-used or not? I.e. new generated ID can be only bigger that all generated before?


回答1:


You don't need to reuse IDs, and shouldn't need to waste time worrying about this. (This is a beginner's database question.)

In general, reusing IDs would technically be possible -- though inconvenient -- but it requires locking the entire table and hence is extremely inefficient for concurrent/ multiuser use.

Also, recovered IDs would not be a contiguous range.. and thus inefficient to represent.

No serious database system implements such a scheme.


So, don't worry about recovery. Just ensure your allocated key-type (integer or long) has enough capacity (2 billion for INTEGER, 2^63 for long/BIGINT) that it will suffice for 200+ years of use at the largest reasonably possible transaction volumes.

For example, at a current 10,000 records per day volume:

  • 3.65 million per year
  • times 20 for business growth = 73 million per year
  • times 200 years = 14.6 billion

This is only ~34 bits -- too big for 'int', but using a long (63 bits positive) it gives you spare capacity by a factor of 2^29 (~500 million) times.

You can then tell your boss that key recovery is not necessary, and the system is confidently projected not to run out of keys anytime in the next 100 billion years.



来源:https://stackoverflow.com/questions/18031469/jpa-reuse-of-deleted-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!