JPA primary key auto generate

后端 未结 2 2046
时光取名叫无心
时光取名叫无心 2020-12-08 08:27

my primary key entity look like below

@GeneratedValue(strategy= GenerationType.TABLE)
private Long id;

when i run, i get error

cou

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 09:14

    There are 4 strategies for auto generation in JPA:

    • Auto
    • Identity
    • Sequence
    • Table

    For Oracle auto generation primary key annotation, Sequence and Table are your choices. The basic logic is to define a generator first, use @SequenceGenerator or @TableGenerator respectively, then use the generator as attribute in @GeneratedValue.

    This is a sample of how to use Sequence strategy:

      @Id
      @SequenceGenerator(name="SEQ_GEN", sequenceName="SEQ_JUST_FOR_TEST", allocationSize=1)
      @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_GEN")
      private long id;
    

    Here is an example of how to use table strategy:

      @Id
      @TableGenerator(name="TABLE_GEN",table="T_GENERATOR", pkColumnName = "GEN_KEY", pkColumnValue = "MONITOR2012.T_JUST_FOR_TEST", valueColumnName = "GEN_VALUE", initialValue = 1, allocationSize = 1 )
      @GeneratedValue(strategy = GenerationType.TABLE, generator="TABLE_GEN")
      private long id;
    

    If no generator specified in @GeneratedValue annotation, the choice will leave to the JPA implementation.

    If you are working on database with existing tables, make sure you the sequence or the table defined in database before you run your application. The table generator will also need you to insert a line to the table before the @GeneratedValue annotation can work properly.

    Here is a tutorial about how to configure primary key auto generation in JPA for Oracle database.

提交回复
热议问题