JPA Tutorial – Entities and primary keys

Introduction

Entity is the lightweight domain object, usually instance of this entity represents one row in the database and its properties represent one table column. It is important to know how to map property of the class to the column of the database table. In this tutorial I am going to show you the details that you can use in your own projects.

Entity

Declaring the entity is done using JPA annotation @Entity, this annotation can be combined with other annotations like @Table.

In this example above we have declared one entity named Pomodoro that is saved into table with specified name PM_POMODORO .

Unique indexes can be also added by setting UniqueConstraint  like in the above example.

Primary keys

Every entity should have primary key, additionally primary key should be taken into account in equals and toHash methods.

Declaring property of the class to be primary key is done using annotation @Id . When no additional annotations are used then application must specify primary key value. Primary key can also be auto generated by specifying @GeneratedValue with desired strategy.

Primary key generation strategies can be :

  • AUTO (default) this is default option. Depending of the database server it can be identity or sequence. Default option for MySQL, SQLite and MsSQL is IDENTITY and SEQUENCE for Oracle and PostgreSQL
  • IDENTITY, is similar to AUTO. Next value is generated and it is increased by 1.
  • SEQUENCE
  • TABLE

Sequence primary key generation strategy can be specified using next example

Now instead of using identity custom sequence generation is used that is in this case incremented by 3.

Table primary key generation is similar to sequence strategy, but sequence is simulated using table.

 

Composite primary keys

Primary keys can be composite and be consisted of two or more columns. Here is an example where we have two properties annotated with @Id.

Another way of specifying composite primary key is by using @EmbedableId and @Embedable. Here is how to do this:

You can notice that I have replaced properties id and projectId with property of type CompositeId. Here is the implementation of this class. What is important is that it implements Serialisable interface and is annotated with @Embeddable.

 

JPA supports numberous types for primary key property, here is a list of java types that can be used for primary keys.

  • Java primitive types
  • Java primitive wrapper types
  • java.lang.String
  • java.util.Date (the temporal type should be DATE)
  • java.sql.Date
  • java.math.BigDecimal
  • java.math.BigInteger

Additionally primary key type should not be of any floating-point type.

 

This is is what relates to primary keys in JPA, stay tuned for other JPA related posts.