Skip to main content

Hibernate Notes



 

  • The Hibernate project has the structure as shown in the figure as above.
  • We need one hibernate.cfg.xml file for hibernate configuration which handles connection pulling and other stuff like driver name, username of the database, password of the database, and the following properties..

Hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
  <property name="hibernate.connection.driver_class">

com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">

jdbc:mysql://localhost/hibernatetutorial</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password"></property>
  <property name="hibernate.connection.pool_size">10</property>
  <property name="show_sql">true</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <!-- Mapping files -->
  <mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>

  • Here the Hibernate tutorial is the database supposed to be created at local host.
  • The dialect property says that we are suing the MySQL database.
  • The show sql property lets us see the comments at the console which ultimately increases readability.
  • Every Class file having the attributes have a classname.hbm.xml file which is the conf file for mapping between POJO and the database. For example we have "contact.hbm.xml" file for contact class.
  • Hibernate accesses all the data through POJO objects and then interacts with the database. For interacting with the database it uses the HQL(Hibernate Query Language)
  • Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column.

Code for Contact.java:


/**
  * Java Class to map to the datbase Contact Table
 */
public class Contact {
  private String firstName;
  private String lastName;
  private String email;
  private long id;

  /**
 @return Email
 */
  public String getEmail() {
  return email;
  }

  /**
 @return First Name
 */
  public String getFirstName() {
  return firstName;
  }

  /** 
 @return Last name
 */
  public String getLastName() {
  return lastName;
  }

  /**
 @param string Sets the Email
 */
  public void setEmail(String string) {
  email = string;
  }

  /**
 @param string Sets the First Name
 */
  public void setFirstName(String string) {
  firstName = string;
  }

  /**
 @param string sets the Last Name
 */
  public void setLastName(String string) {
  lastName = string;
  }

  /**
 @return ID Returns ID
 */
  public long getId() {
  return id;
  }

  /**
 @param l Sets the ID
 */
  public void setId(long l) {
  id = l;
  }
}

Mapping the Contact class with the Contact Table.

Code for Contact.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="roseindia.tutorial.hibernate.Contact" table="CONTACT">
   <id name="id" type="long" column="ID" >
   <generator class="assigned"/>
  </id>

  <property name="firstName">
   <column name="FIRSTNAME" />
  </property>
  <property name="lastName">
  <column name="LASTNAME"/>
  </property>
  <property name="email">
  <column name="EMAIL"/>
  </property>
 </class>

</hibernate-mapping>


 


 

Then we need to create a hibernatetutorial database using MySQL running at localhost.

For updating or inserting the data in the database we first need to create the session of hibernate. For that we need to use hibernate session factory which returns the session for hibernate.

The hibernate-session is the main runtime interface between java and Hibernate.

The most important method for this is sessionobj.save(POJOobject);.

The code for FirstExample.java

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


/**

 * Hibernate example to inset data into Contact table
 */
public class FirstExample {
  public static void main(String[] args) {
  Session session = null;

  try{
  // This step will read hibernate.cfg.xml 

and prepare hibernate for use
  SessionFactory sessionFactory = new 

Configuration().configure().buildSessionFactory();
 session =sessionFactory.openSession();
  //Create new instance of Contact and set 

values in it by reading them from form object
 System.out.println("Inserting Record");
  Contact contact = new Contact();
  contact.setId(3);
  contact.setFirstName(
"Utkarsh");
  contact.setLastName(
"Thakkar");
  contact.setEmail(
"yjk@yahoo.com");
  session.save(contact);
  System.out.println("Done");
  }catch(Exception e){
  System.out.println(e.getMessage());
  }finally{
  // Actual contact insertion will happen at this step
  session.flush();
  session.close();

  }
  
  }
}

Popular posts from this blog

Primitive Obsession with Example

Primitive Obsession is the name of a code smell that occurs when we use primitive data types to represent domain ideas. For example, we use a string to represent a message or an integer to represent an amount of money. For Example: Code with Primitive Obsession // primitiveObsession.java public class primitiveObsession { public static void main ( String args []) { Integer [] cityPopulations = { 13000000 , // London 21903623 , // New York 12570000 , // Tokyo 1932763 , // Stockholm 1605602 , // Barcelona 4119190 // Sydney }; for ( Integer cityPopulation : cityPopulations ) { System . out . println ( cityPopulation ); } } } public class City { private final String name ; private final int population ; private final Continent continent ; public String getName () { return name ; } public int getPopulation () { return population ; } public Continent ge

Singleton Pattern

Lazy Initialization :- The instantiation of an object can be delayed until it is actually needed. Usage: This especially beneficial when the constructor is doing a costly job like, accessing a remote database. Example: This code demonstrates how the Singleton pattern can be used to create a counter to provide unique sequential numbers, such as might be required for use as primary keys in a Database:   Sequence.java   public class Sequence { private static Sequence instance; private static int counter; private Sequence() { counter = 0; // May be necessary to obtain // starting value elsewhere... } public static synchronized Sequence getInstance() { if(instance==null) // Lazy instantiation { instance = new Sequence(); } return instance; } public static synchronized int getNext() { return ++counter; } }   Some things to note about this implementation: Synchronized methods are used to ensure that the class is thread-safe. This class cannot be subclassed because the constructor is private