Hibernate and Relationship

Hibernate
Introduction
Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open source persistent framework .
Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from 95% of common data persistence related programming tasks.
Hibernate sits between traditional Java objects and database server to handle all the work in persisting those objects based on the appropriate O/R mechanisms and patterns.







 Advantages:
·         Hibernate takes care of mapping Java classes to database tables.
·         Provides simple APIs for storing and retrieving Java objects directly to and from the database.
·         Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects.
·         Manipulates Complex associations of objects of your database.
·         Minimize database access with smart fetching strategies.
·         Provides Simple querying of data.
Hibernate Architecture:
The Hibernate architecture is layered to keep you isolated from having to know the underlying APIs. Hibernate makes use of the database and configuration data to provide persistence services (and persistent objects) to the application.
Following is a very high level view of the Hibernate Application Architecture.
Following is a detailed view of the Hibernate Application Architecture with few important core classes.
Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality common to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers.   
Following section gives brief description of each of the class objects involved in Hibernate Application Architecture.
Configuration Object:
The Configuration object is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate. The Configuration object provides two keys components:
·         Database Connection: This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml.
·         Class Mapping Setup. This is achieved by using hbm.xml file or by Annotations.

This component creates the connection between the Java classes and database tables.

SessionFactory Object:
Configuration object is used to create a SessionFactory object which intern configures Hibernate for the application using the supplied configuration file and allows for a Session object to be instantiated. The SessionFactory is a thread safe object and used by all the threads of an application.
The SessionFactory is heavyweight object so usually it is created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file. So if you are using multiple databases then you would have to create multiple SessionFactory objects.
·         Read
·         Check db
·         Connection into memory
·         Parse all hbm files
·         Corresponding tables exist
Session Object:
A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.
Transaction Object:
A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA).
This is an optional object and Hibernate applications may choose not to use this interface, instead managing transactions in their own application code.
Query Object:
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.
Criteria Object:
Criteria object are used to create and execute object oriented criteria queries to retrieve objects.
Hibernate Relationships:
Using hibernate, if we want to put relationship between two entities [objects of two pojo classes], then in the database tables, there must exist foreign key relationship, we call it as Referential integrity.
One-To-One
A one-to-one relationship occurs when one entity is related to exactly one occurrence in another entity.
@Entity
public class Body {
    @Id
    private Long id;
 
    @OneToOne(cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn
    private Heart heart;
 
    ...
}            
@Entity
public class Heart {
    @Id
    public Long getId() { ...}
}            

 

One-To-Many        
It is a type of relationship in which each record in one table is linked to multiple records in another table.


@Entity
public class Troop {
    @OneToMany(mappedBy="troop")
    private Set<Soilder> soldiers;
    ...                                  
}
 
@Entity
public class Soldier {
    @ManyToOne   
    @JoinColumn(name="troop_fk")
    Private Troop troop;
    ...
} 

Many-to-one         
Many-to-one associations are declared at the property level with the annotation @ManyToOne:
@Entity
public class Flight implements Serializable {
    
 @ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
 @JoinColumn(name="COMP_ID")
 private Company company();
    ...
}   

Many-to-Many     
It is a logical data relationship in which the value of one data element can exist in combination with many values of another data element, and vice versa.

@Entity
@Table(name="EMPLOYEE")
public class Employee {         
    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(name="EMPLOYEE_MEETING", 
    joinColumns={@JoinColumn(name="EMPLOYEE_ID")}, 
    inverseJoinColumns={@JoinColumn(name="MEETING_ID")})
    private Set<Meeting> meetings = new HashSet<Meeting>();
    ...
}
@Entity
@Table(name="MEETING")
public class Meeting {        
    @ManyToMany(mappedBy="meetings")
    private Set<Employee> employees = new HashSet<Employee>();
    ...
}
 

Hibernate Annotations:
@Entity
This annotations is used to mark a class as an Entity bean.
@Table
The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database.
@ID and @Generated Value
Each entity bean will have a primary key, which you annotate on the class with the @Id annotation. The primary key can be a single field or a combination of multiple fields depending on your table structure.
By default, the @Id annotation will automatically determine the most appropriate primary key generation strategy to be used but you can override this by applying the @GeneratedValue annotation which takes two parameters strategy and generator. Preferred way is to use only default the default key generation strategy. Letting Hibernate determine which generator type to use makes your code portable between different databases.

@Column
The @Column annotation is used to specify the details of the column to which a field or property will be mapped. You can use column annotation with the following most commonly used attributes:
·         name attribute permits the name of the column to be explicitly specified.
·         length attribute permits the size of the column used to map a value particularly for a String value.
·         nullable attribute permits the column to be marked NOT NULL when the schema is generated.
·         unique attribute permits the column to be marked as containing only unique values.

Example:

@Entity
@Table(name = "EMPLOYEE")
public class Employee {
   @Id
   @GeneratedValue
   @Column(name = "id")
   private int id;

   @Column(name = "first_name")
   private String firstName;

   @Column(name = "last_name")
   private String lastName;

   @Column(name = "salary")
   private int salary; 

   public Employee() {}
   public int getId() {
      return id;
   }
   public void setId( int id ) {
      this.id = id;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName( String first_name ) {
      this.firstName = first_name;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName( String last_name ) {
      this.lastName = last_name;
   }
   public int getSalary() {
      return salary;
   }
   public void setSalary( int salary ) {
      this.salary = salary;
   }
}

Share this: