Learn about @Id annotation in JPA

In this tutorial, I will cover one of the basic annotations to work with mapping the columns of tables in the database, that is the @Id annotation in JPA.

We will go straight into the problem.

This annotation is declared to determine where the primary key attribute of the entity corresponds to the primary key column in the table. For example, we usually take the column id as the primary key in the table, when mapping with the Java entity object, we will add the @Id annotation associated with the corresponding column id attribute.

For example, we have the following entity:

An entity must have at least one primary key attribute associated with @Id annotation. If you do not declare any @Id annotation, when running you will encounter errors immediately.

For example, if I now comment on the @Id annotation of the id attribute in Clazz class, following error will happen:

We can use multiple Java data types for the primary key attribute of the entity. As follows:

  • Primitive: byte, int, short, long, char.
  • Wrapper of primitive: Byte, Integer, Short, Long, Character.
  • String, BigInteger.
  • java.util.Date, java.sql.Date

In addition, we can also use floats and doubles as well as wrappers for these primitives, such as Float, Double, BigDecimal, but these data types should not be used because these are decimal values, easy to have error when rounding.



Add Comment