Home > Enterprise >  What is the use of the field generator in @GeneratedValue in JPA / Hibernate?
What is the use of the field generator in @GeneratedValue in JPA / Hibernate?

Time:10-29

when you create an id like

@Id
@GeneratedValue(generator = "increment")
private Long Id;

what is the role of generator field? what is the meaning of generator?

and should any implementation of JPA provide for all types of generators : example generator = "increment"?

CodePudding user response:

It's a way to create unique ids. Different databases provide different ways to create unique ids. In other words, Hibernate/JPA will put a value on that field automatically when a new row is saved. For example mysql provides autoincrement columns (strategy=identity), while oracle provides sequences (strategy=identity).

If the database doesn't provide any of the features above, the strategy table uses a table created by JPA which is used to create unique, monotonically incremented numbers in a safe way at the cost of extra queries to the database.

The documentation from hibernate on this topic is really, really good and worth a read... and also Hibernate has a ton more features than JPA, which are good to know.

CodePudding user response:

It says here in the doc: https://docs.oracle.com/javaee/6/api/javax/persistence/GeneratedValue.html#generator()

generator field is where you specify: The name of the primary key generator to use as specified in the SequenceGenerator or TableGenerator annotation.

But in the example I gave (increment), it's more than that, you can use the field to specify one of hibernate generators, which are not part of JPA.

increment is one of them. if you want to find out more about them look here : https://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e2614

  • Related