Hibernate: rundown on how @GeneratedValue works

前端 未结 2 499
难免孤独
难免孤独 2020-12-03 14:47

I am having troubling finding an accurate explanation of @GeneratedValue and the different strategies regarding on what happens from a database point of view.

Will

相关标签:
2条回答
  • 2020-12-03 15:18

    I am assuming you are refering to the JPA @GeneratedValue.

    The @GeneratedValue annotation tells the ORM how to figure out the value of that field.

    For example:

     @Id
     @GeneratedValue(strategy=SEQUENCE, generator="CUST_SEQ")
     @Column(name="CUST_ID")
     public Long getId() { return id; }
    
     Example 2:
    
     @Id
     @GeneratedValue(strategy=TABLE, generator="CUST_GEN")
     @Column(name="CUST_ID")
     Long id;
    

    The key thing to understand is that a generated value has a strategy and the strategy of the generated value determines what happens. In the above example the SEQUENCE generation strategy means that the ORM will ask the database for a new value for the sequence when saving an object for the first time. The second example specify a table generation strategy which means that the ORM will consult a row in a table to determine the value of a id. In example example 2 the details of which table is used are not show since it reference a generator called "CUST_GEN"

    Typcial generators you will run into.

    • Identity - After an insert ask the auto incerement column for the value of the item
    • Sequence - the value comes from a db sequence
    • table - the value comes from another table in the database
    • auto - pick one of the above based on the database type
    • UUID - generate a UUID before doing an insert

    It is possible to develop custom generator. The interaction with the database will depend on generation strategy.

    0 讨论(0)
  • 2020-12-03 15:24

    Please use http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/ link for reference. But if you will tell what specific you are looking for I might be able to help you better. Here is little detail about @GeneratedValue annotation… I love this blog post on same topic http://elegando.jcg3.org/2009/08/hibernate-generatedvalue/. He has done good job explaining.

    0 讨论(0)
提交回复
热议问题