lishman levelup
«previous  next»

Getting Started

Hibernate Entities

Suppose we have this table:

Using Hibernate, we can map a POJO class to the table like this:
public class Country {

  private Integer id;

  private String name;

  private int area;

  private int rank;

  // Accessors

@Entity designates the class as a Hibernate entity which maps to the database table specified in the @Table annotation.

@Id identifies the entity's primary key and @GeneratedValue automatically supplies an appropriate value for the column when inserting a new row.

XML Mapping
Mapping metadata can also be specified in separate XML documents. However, this tutorial will focus only on annotations.
By default, all fields of the class are mapped to table columns with the same name. Use the @Column annotation when the field and column names differ, or the @Transient annotation if a field is not to be persisted. Be sure to use a wrapper class rather than a primitive if the database column is nullable. Hibernate will throw an exception if an attempt is made to load a null value into a field with a primitive type.

Hibernate uses convention over configuration to apply sensible defaults in the absence of annotations. The area field is automatically mapped to the AREA column and the @Table annotation is, in fact, optional in this case because the class name and table name are the same.

Annotate methods rather than fields to instruct Hibernate to manipulate variables using their accessors.
public Integer getId() {
  return id;