lishman levelup
«previous  next»


Getting Started
Associations
HQL




Hibernate Query Language


Hibernate Query Language (HQL) is an object oriented query language which is derived from SQL. However, instead of naming database tables and columns in a query, Java classes and properties are used instead.
 
select cont.countries from Continent cont where cont.name = 'Europe'
 
Hibernate converts HQL into the appropriate native SQL for the database and populates persistent objects with the results of the query.

HQL supports selection and projection as you would expect, but also includes more advanced features such as aggregation, joins, subqueries and pagination.

In this section, we use the CONTINENT and COUNTRY model shown below to demonstrate the various features of HQL:



We map these persistent classes to the tables:
@Entity
@Table(name = "CONTINENT")
public class Continent {

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

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

  @OneToMany(mappedBy = "continent")
  @JoinColumn(name="CONT_ID")
  private Set<Country> countries = new HashSet<Country>();

  // Accessors

}
@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;

  @Column(name="POP")
  private long population;

  @Column(name="POP_UPD_ON")
  private Date populationUpdatedOn;

  @Transient
  private int rank;

  private String currency;

  @ManyToOne (fetch=FetchType.LAZY)
  @JoinColumn(name="CONT_ID")
  private Continent continent;

  // Accessors

}
The fetch type on the @ManyToOne mapping is set as LAZY to reduce the amount of SQL generated and make the output easier to read.
»