136
@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY)

Why we are using this annotations? i need to know if this autoincrement my table id values. (GenerationType.IDENTITY) is there any other types whats actually happening when we use this annotation

public class Author extends Domain
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id") 
    private Integer id;

    @Basic(optional = false)
    @Column(name = "name") 
    private String name;

    @Column(name = "address") 
    private String address; 

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "authorId")
    private List<Book>
    bookList;

    public Author()
    { 
        setServiceClassName("wawo.tutorial.service.admin.AuthorService");
    }
}

*Is it necessary to extend Domain abstract class?What is the use?

1

5 Answers 5

183

First of all, using annotations as our configure method is just a convenient method instead of coping the endless XML configuration file.

The @Idannotation is inherited from javax.persistence.Id, indicating the member field below is the primary key of current entity. Hence your Hibernate and spring framework as well as you can do some reflect works based on this annotation. For details, please check javadoc for Id

The @GeneratedValue annotation is to configure the way of increment of the specified column(field). For example, when using Mysql, you may specify auto_increment in the definition of table to make it self-incremental, and then use

@GeneratedValue(strategy = GenerationType.IDENTITY)

in the Java code to denote that you also acknowledged to use this database server side strategy. Also, you may change the value in this annotation to fit different requirements.

1. Define Sequence in database

For instance, Oracle has to use sequence as increment method, say we create a sequence in Oracle:

create sequence oracle_seq;

2. Refer the database sequence

Now that we have the sequence in database, but we need to establish the relation between Java and DB, by using @SequenceGenerator:

@SequenceGenerator(name="seq",sequenceName="oracle_seq")

sequenceName is the real name of a sequence in Oracle, name is what you want to call it in Java. You need to specify sequenceName if it is different from name, otherwise just use name. I usually ignore sequenceName to save my time.

3. Use sequence in Java

Finally, it is time to make use this sequence in Java. Just add @GeneratedValue:

@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")

The generator field refers to which sequence generator you want to use. Notice it is not the real sequence name in DB, but the name you specified in name field of SequenceGenerator.

4. Complete

So the complete version should be like this:

public class MyTable
{
    @Id
    @SequenceGenerator(name="seq",sequenceName="oracle_seq")        
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")               
    private Integer pid;
}

Now start using these annotations to make your JavaWeb development easier.

6
  • 3
    The proper syntax of annotation SequenceGenerator for Oracle 11.2 is @SequenceGenerator(name="seq", sequenceName="ORACLE_SEQ", allocationSize=1). Otherwise without allocationSize parameter it gives very strange generated results (in my case negative).
    – hariprasad
    Mar 18, 2017 at 17:31
  • @hariprasad In my case if I don't set it, the increment is 10. But still this is an optional parameter.
    – Rugal
    Mar 23, 2017 at 22:30
  • One of my friend said @Id is for uniquely identitfy. If you will follow code first approach then it will be primary key else difference. can you explain the above said sentence? Feb 8, 2019 at 9:32
  • @PSatishPatro Correct, Id is for unique record of course. But we will always have such stuff in table definition, even for NoSQL
    – Rugal
    Feb 15, 2019 at 20:52
  • 1
    @SatishPatro According to Javadoc, it is used for primary key
    – Rugal
    Jan 7, 2022 at 12:47
39

Simply, @Id: This annotation specifies the primary key of the entity.

@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used.

GenerationType enum defines four strategies:

  1. Generation Type. TABLE,
  2. Generation Type. SEQUENCE,
  3. Generation Type. IDENTITY
  4. Generation Type. AUTO

GenerationType.SEQUENCE

With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities.

GenerationType.TABLE

With this strategy, the underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities.

GenerationType.IDENTITY

This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.

GenerationType.AUTO

This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used.

Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html

1
  • I was getting an error on the tests that only after running in debug mode could I find it was due to a Feature not supported: TIMESTAMP(6) for a field marked as Timestamp but, oh surprise, it had nothing to do with it but with the fact that, as you mention, h2 doesn't support GenerationType.IDENTITY Mar 26 at 9:53
33

In a Object Relational Mapping context, every object needs to have a unique identifier. You use the @Id annotation to specify the primary key of an entity.

The @GeneratedValue annotation is used to specify how the primary key should be generated. In your example you are using an Identity strategy which

Indicates that the persistence provider must assign primary keys for the entity using a database identity column.

There are other strategies, you can see more here.

4
  • 12
    "Indicates that the persistence provider must assign primary keys for the entity using a database identity column."can you expalain this
    – Lijo
    Dec 16, 2013 at 5:17
  • 3
    @404 One strategy databases use for generating their primary keys is to keep a table with a column (YMMV) where they only store assigned ids. When a new row has to be entered, a new id will be generated and used that was not originally in the table. Dec 16, 2013 at 5:27
  • 1
    so auto incrementing of id is it?
    – Lijo
    Dec 16, 2013 at 5:31
  • 2
    @404 I think it depends on the database. With MySQL that's what it seems like, but it might be different with other DBs. Dec 16, 2013 at 5:33
5

Why are we using this annotation?

  • First I would like to remind everyone that the annotations, such as @Id, are providing metadata to the persistence layer(I will assume hibernate).This metadata will most likely be stored in the .class file(but not stored in the database) and is used to tell hibernate how to recognize, interpret and manage the entity. So, Why are you using the annotation? To provide your persistence layer with the proper information about how to manage the entity.

Why use the @Id annotation?

  • The @Id annotation is one of the two mandatory annotations needed when creating an entity with JPA. The other one being @Entity. @Id does two things for us:

    1) signifies that this field will be the unique identifier for this class when mapped to a database table

    2) the presence of @Id lets the persistence layer know that all other fields within this class are to be mapped to database rows

Why use @GeneratedValue?

  • By marking the @Id field with @GeneratedValue we are now enabling id generation. Which means that the persistence layer will generate an Id value for us and handle the auto incrementing. Our application can choose 1 of 4 generations strategies:

    1) AUTO

    2) TABLE

    3) SEQUENCE

    4) IDENTITY

  • If not strategy is specified then AUTO is assumed

What is strategy = GenerationType.IDENTITY actually doing?

  • When we specify the generation strategy as GenerationType.IDENTITY we are telling the persistence provider(hibernate) to let the database handle the auto incrementing of the id. If you were to use postgres as an underling database and specified the strategy as IDENTITY, hibernate would execute this:
create table users (
       id  bigserial not null,
        primary key (id)
    )

  • Notice that they type of the id is bigserial, what is bigserial? As per the postgres documentation, bigserial is a large autoincrementing integer.

Conclusion

  • By specifying:
@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

  • you have told the underlying persistence layer to use the id field as a unique identifier within the database. Also told the persistence layer to let the database handle the auto incrementing of the id with GenerationType.IDENTITY.
0

In very simple words, we want to tell our Database (DB) what strategy to use to generate primary keys. Now, primary keys must be different for every different row so there must be some strategy that will tell the DB on how to differentiate one row from another.

GenerationType lets us define that strategy.

Here @GeneratedValue(stratergy=GenerationType.IDENTITY) is telling our DB to store primary key in the identity column which is a default column in SQL for default auto incremented primary key generation.

1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Sep 30, 2022 at 3:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.