Hibernate custom primary key policy

Source: Internet
Author: User

Hibernate custom primary key policy,
In the latest project, use the guid generation policy of hibernate. The configuration is as follows:
<Id name = "id" type = "java. lang. String">
<Column name = "ID" length = "32"/>
<Generator class = "guid"/>
</Id>
We found that the generated IDs are quite regular. First, we can see that the guid of the source hibernate uses the guid algorithm mechanism at the bottom layer of the database, which corresponds to the uuid () function of MYSQL and SQL

Server's newid () function, ORACLE's rawtohex (sys_guid () function, and so on.


Specifically, oracle uses (select rawtohex (sys_guid () from dual)
Use the following pl/SQL test:


Declare
V varchar2 (32 );
Begin
For I in 0 .. 10 loop
Select rawtohex (sys_guid () into v from dual;
Dbms_output.put_line (v );
End loop;
End;


Result:
A36190EE69DDAAE7E040200A8A096CE5
A36190EE69DEAAE7E040200A8A096CE5
A36190EE69DFAAE7E040200A8A096CE5
A36190EE69E0AAE7E040200A8A096CE5
A36190EE69E1AAE7E040200A8A096CE5
A36190EE69E2AAE7E040200A8A096CE5
A36190EE69E3AAE7E040200A8A096CE5
A36190EE69E4AAE7E040200A8A096CE5
A36190EE69E5AAE7E040200A8A096CE5
A36190EE69E6AAE7E040200A8A096CE5
A36190EE69E7AAE7E040200A8A096CE5
Only one character in the middle is different.

The following uses the hibernate custom id policy interface IdentifierGenerator
For the sake of simplicity, use the uuid method that comes with jdk:

 

Public class UUIDGenerator implements IdentifierGenerator {

Private static Logger logger = Logger. getLogger (UUIDGenerator. class );
 
Public Serializable generate (SessionImplementor session, Object object)
Throws HibernateException {
String id = UUID. randomUUID (). toString (). replaceAll ("-", ""). toUpperCase ();

Return id;
}

}


Use the following configuration during Configuration:

<Id name = "id" type = "java. lang. String">
<Column name = "ID" length = "32"/>
<Generator class = "com. XXX. XXX. UUIDGenerator"/>
</Id>
~ End ~

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.