Thursday, March 25, 2010

Constructing table views with Hibernate

Database views are convenient to use especially for a view that represents a complex query or one that is used repetitively.

Here I will show you how to construct a database view using Hibernate.

In the HBM mapping file you can declare your view using the element subselect.
The SQL used should be native to the database you are using and should not be HQL.

You use the synchronize elements to identify which tables the SQL query uses to construct the view.

Below is an example:

   <!-- VIEW -->
    <class name="" >
        <!-- Postgres specific SQL call -->
            SELECT '' || ||  AS id, AS strain_id, AS cryosession_id 
            FROM cryo_session cs 
            JOIN cryo_session_result csr ON( 
            JOIN mouse m ON ( 
            JOIN strains s ON ( 
            GROUP BY cs.date_of_session,, 
            ORDER BY cs.date_of_session
        <synchronize table="cryo_session"/>        
        <synchronize table="cryo_session_result"/>
        <synchronize table="mouse"/>
        <synchronize table="strains"/>
        <id name="id" type="java.lang.Long" />

        <many-to-one name="strain" column="strain_id" cascade="none" not-null="true" />
        <many-to-one name="cryoSession" column="cryosession_id" cascade="none" not-null="true" />

I combine two foreign key ID's to construct a unique key for the table view as follows:
'' || ||

The entity representing the view is a simple POJO as follows:

public class StrainCryo {

     * Arbitrary ID to create the view in Hibernate
    private Long id;
    private Strain strain;
    private CryoSession cryoSession;
    public Long getId() {
        return id;
    public void setId(Long id) { = id;
    public Strain getStrain() {
        return strain;
    public void setStrain(Strain strain) {
        this.strain = strain;
    public CryoSession getCryoSession() {
        return cryoSession;
    public void setCryoSession(CryoSession cryoSession) {
        this.cryoSession = cryoSession;

1 comment:

  1. Its a nice & useful post. Because as Joomla Web Developer I think its not that easy to create table views hibernation.Thanks for sharing