Version: hibernate-3.2.7
One method: Use uuid to generate a unique primary key. In this way, if the Object id is null, a UUID is automatically generated during storage. If the id is not null, this record is located in the database and then updated. If not found, an exception is thrown.
Xxxclass. hbm. xml Code
- <Id name ="Id"Type ="Java. lang. String"Column ="ID">
- <Generator class ="Uuid. hex"/>
- </Id>
Xxxclass. java code
- Public class XXXClass {
- /** Id */
- Private String id;
- Public void setId (String id ){
- This. id = id;
- }
- Public String getId (){
- Return id;
- }
- }
Method 2: Use org. hibernate. id. UUIDHexGenerator generates a unique primary key. In this way, if the Object id is null, a UUID is automatically generated during storage. If the id is not null, this record is located in the database and updated. If no record is found, insert is executed.
Xxxclass. hbm. xml Code
- <Id name ="Id"Type ="Java. lang. String"Column ="ID">
- <Generator class ="AssignCopiedId"/>
- </Id>
Xxxclass. java code
- Public class XXXClass implements AssignedIdModel {
- /** Id */
- Private String id;
- Public void setId (String id ){
- This. id = id;
- }
- Public String getId (){
- Return id;
- }
- @ Override
- Public String getAssignedId (){
- Return assignedId;
- }
- Public void setAssignedId (String assignedId ){
- This. assignedId = assignedId;
- }
- }
Assignedidmodel. java code
- Public interface AssignedIdModel {
- Public String getAssignedId ();
- }
Assigncopiedid. java code
- Import org. hibernate. engine. SessionImplementor;
- Import org. hibernate. id. UUIDHexGenerator;
- Public class AssignCopiedId extends UUIDHexGenerator {
- Public Serializable generate (SessionImplementor session, Object obj ){
- If (obj instanceof AssignedIdModel
- & (AssignedIdModel) obj). getAssignedId ()! = Null
- & (AssignedIdModel) obj). getAssignedId (). trim (). length ()>0)){
- Return (AssignedIdModel) obj). getAssignedId ();
- } Else {
- Return super. generate (session, obj );
- }
- }
- }
Conclusion: compared with the two methods, the method 1 is relatively simple and can meet the general situation. It is used in many projects. Method 2 is used when method 1 cannot be processed, for example, when copying table records from other system databases.