How to generate an alphanumeric ID in java?

爷,独闯天下 提交于 2019-12-11 20:38:21

问题


I have a table named GROUPS which has a column GROUP_ID whose values are

GRP001, GRP002, GRP003

and so on. Now every time I insert a new row I have to insert it with a (current) GROUP_ID= (highest)GROUP_ID+ 1 , for example if highest GROUP_ID= GRP003 I have to generate a new GROUP_ID GRP004 when I insert a new row.

How can I do this using java?

I am currently using Hibernate along with Struts 2 in my program

Is there any way to deal with this using hibernate? Or will I have to write additional code to lock the table, check the db for max Id (and then increment it) and finally release the lock?


回答1:


I remember solving a problem similar to this once. What I did was I create a custom primary key generator as supported by hibernate.

This guy explains it clearly here: "Custom Hibernate Primary Key Generator"

Basically you just need to implement org.hibernate.id.IdentifierGenerator and all should be set.

Just be aware that the solution implemented in the example above is database dependent. But I think sometimes common sense should prevail over overengineering.



来源:https://stackoverflow.com/questions/15731407/how-to-generate-an-alphanumeric-id-in-java

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