lishman levelup
«previous  next»


Getting Started
Associations
HQL



Hibernate Entities


Suppose we have this table:
Country Table (COUNTRY_ID, COUNTRY_NAME, AREA)

Using Hibernate, we can map a POJO class to the table like this:
@Entity
@Table(name="COUNTRY")
public class Country {

  @Id
  @GeneratedValue
  @Column(name="CTRY_ID")
  private Integer id;

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

  private int area;

  @Transient
  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.
@Id
@GeneratedValue
@Column(name="CTRY_ID")
public Integer getId() {
  return id;
}
»