Data uniqueness is a common requirement, but it is dangerous if the framework cannot provide relevant control and the programmer has full control. In JPA, there are the following four policies.
A. Automatic container generation --- generatortype. Auto
Automatically Generated by JPA
B. Use the automatic growth field of the database to generate --- generationtype. Identity
The JPA container uses the auto-increment field of the database to assign a unique value to the newly added object. In this case, the database must provide support for self-growth fields, such as SQL Server, MySQL, DB2, and Derby.
C. generate --- generationtype. Sequence Based on the database serial number (sequence)
Indicates that the database serial number is used to assign a unique value to the newly added object. In this case, the database must provide support for serial numbers. In common databases, Oracle support is required.
D. Use fields in the database table to generate --- generationtype. Table
Indicates to use a field in the specified table in the database to record the identifier of the object. This field is used to add a unique value to the newly added object.
Something special
1. Use UUID (two different implementation versions of Hibernate and openjpa are somewhat different)
Openjpa
@ Generatedvalue (Strategy = generationtype. Auto, generator = "UUID ")
Hibernate (eclipse will prompt an error, but the program can run)
@ Genericgenerator (name = "test", strategy = "UUID ")
@ Generatedvalue (generator = "test ")
In fact, these two methods are not very good, because they have something to do with the implementation, it will be more difficult to migrate in the future, so you can directly use Java. util. UUID
User. setuserid (UUID. randomuuid (). tostring ());
2. Use @ generatedvalue (Strategy = generationtype. Identity)
Fields need to be defined in the database (Derby) in this way
User_id bigint not null generated always as identity (start with 1, increment by 1)
3. If the database table field is used to generate --- generationtype. Table
For hibernate, you need to create a table that generates the primary key, but openjpa does not. If not, it is automatically generated.
The Code is as follows:
@ Tablegenerator (name = "test111", table = "idtable ",
Pkcolumnname = "keyid", valuecolumnname = "keyValue", pkcolumnvalue = "testuser_id ")
@ Generatedvalue (Strategy = generationtype. Table, generator = "test111 ")
Create Table idtable (
Keyid varchar (255) not null,
KeyValue bigint,
Primary Key (keyid)
)
(Note: This document is a reference, the original address http://blog.csdn.net/fantian830211/archive/2009/09/11/4544117.aspx)