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

Design Patterns (TID)

The pattern is an organised way of solving some specific class of problems. These patterns come in to the picture at analysis and high-level-design phase. The first step of applying one pattern to the code base is first to understand the find the vector of change in the code base. Next step is to isolate the things that are subject to change form the things that are not. That is adding a layer of abstraction to the code. The goal of design patterns is isolating the changes in your code. Understand Inheritance and Composition as a solution to a specific class of problems. Inheritance : - It allows you to express differences in behavior (that's the thing that changes) in objects that all have the same interface (that's what stays the same). Composition : - Composition can also be considered a pattern, since it allows you to change—dynamically or statically—the objects that implement your class, and thus the way that class works. Some principles of designing the c...

Adobe Firefly

Adobe Firefly is designed to help developers create custom applications more quickly and easily. The platform is built on top of Adobe's existing Experience Cloud, which provides a range of tools for managing customer data and creating personalized experiences. One of the key features of Adobe Firefly is its ability to integrate with a wide range of other technologies and services. This means that developers can use the platform to build applications that connect with everything from social media platforms to IoT devices. Another important aspect of Adobe Firefly is its focus on speed and efficiency. The platform includes a range of pre-built components and templates that developers can use to quickly create new applications. It also includes a range of tools for testing and debugging applications, which can help to speed up the development process. Overall, Adobe Firefly looks like an exciting new platform for developers who are looking to create custom applications quickly and ef...

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...