The Entity Class

The basic unit of persistence in JPA is the entity, which is nothing more than a regular Java class with metadata to describe how its state maps to the database tables.

The metadata can be in the form of annotations or in an xml file. My examples will only include annotation based mappings. XML mappings are getting out of fashion, although they might come in handy in a few scenarios.

  • Every Class that is to be mapped must be annotated with @Entity. We will call such classes Entity Classes.
  • All the Entity classes must have a identity field annotated with @Id that maps to a primary key. It is a good idea to use Surrogate keys.
  • JPA has lots of defaulting rules that takes care of table & field naming conventions. So there is no need to explicitly specify them.

A simple entity class would look like the following

@Entity
public class User {
    
    @Id
    int id;
    
    String name;

}

Now let's move on to managing our entity with the EntityManager