JPA -- Identifier Generation

GenerationType enumerated: AUTO, TABLE, SEQUENCE, IDENTITY

AUTO

@Entity
public class Employee{
  @Id @GeneratedValue(stretegy = GenerationType.AUTO)
  private int ID;
}

TABLE

@Id @GeneratedValue(stretegy = GenerationType.TABLE)
private int ID;

@TableGenerator(name = "Eem_Gen",
    table = "ID_GEN",
    pkColumnName = "GEN_NAME",
    valueColumnName = "GEN_VAL")

@TableGenerator(name = "Address_Gen", 
    table = "ID_GEN",
    pkColumnName = "GEN_NAME",
    valueColumnName = "GEN_VAL",
    pkColumnValue = "Addr_Gen",
    initialValue = 10000,
    allocationSize = 100)
@Id @GeneratedValue(generator = "Address_Gen")
private int id;

CREATE TABLE id_gen(
    gen_name VARCHAR(80),
    gen_val INTERGER,
    CONSTRAINT pk_id_gen PRIMARY KEY(gen_name)
);
INSERT INTO id_gen (gen_name, gen_val) VALUES ('Emp_Gen', 0);
INSERT INTO id_gen (gen_name, gen_val) VALUES ('Addr_Gen', 10000);

@Entity
@TableGenerator(name="tab", initialValue=0, allocationSize=50)
public class EntityWithTableId {
    @GeneratedValue(strategy=GenerationType.TABLE, generator="tab")
    @Id long id;
}

A good practice would be to define @TableGenerator locally on the id attribute if only one class is using it but to define it in XML, if it will be used for multiple classes;

allocationSize: To avoid updating the row for every single identifier that gets requested, an allocation size is used. This will cause the provider to preallocate a block of identifiers and then give out identifiers ffrom memory as rquested until the block is used up. Default value for it is 50.

TIP: You should check your JPA provider document to see how it can avoid the risk of deadlock when concurrent threads are creating entities and locking resources.

SEQUENCE: Using Database internal mechanism for ID generation called sequences.

@Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;


@SequenceGenerator(name = "Emp_Gen", sequenceName = "Emp_Seq")
@Id @GeneratedValue(generator = "Emp_Gen")
private int id;


CREATE SEQUENCE Emp_Seq
    MINVALUE 1
    START WITH 1
    INCREMENT BY 50

IDENTITY

@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

some databases support a primary key identity column, sometimes referred to as an autonumber column.

Identity is often used when database sequences are not supported by the database or because a legacy schema has already defined the table to use identity columns.

你可能感兴趣的:(java,jpa)