Java ORM: Hibernate example

Hibernate is

Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.

Hibernate’s primary feature is mapping from Java classes to database tables (and from Java data types to SQL data types). Hibernate also provides data query and retrieval facilities. Hibernate generates the SQL calls and attempts to relieve the developer from manual result set handling and object conversion and keep the application portable to all supported SQL databases with little performance overhead.

well, as we know what is hibernate and what is the primary feature is, let’s go deeper from developers’ perspective, inspecting three areas:

  1. Configuring hibernate for your application: please note that I will configure hibernate as a stand alone database layer, don’t assume I am getting it ready for production use into web application.
  2. Querying a database: single simple queries to complex joins.
  3. Updating a database using save and update.

In this article we will do hibernate configuration with simple DB interaction, persisting data. I will cover different ways of query DB and updating/saving data to DB in later articles.

 

Getting ready, Organized!

Simply open your preferred Java IDE and start a new Java project and create a lib directory that will contain required jars for our application and config directory that will contain any config files we might need.

your application hierarchy should look something like this

eclipse IDE, Simple Hibernate application

 

now, let’s start the real work

  • create users table on database, that we will use as an example to interact with DB.
CREATE TABLE  `example_db`.`users` (
`id` INT NOT NULL AUTO_INCREMENT ,
`username` VARCHAR( 255 ) NOT NULL ,
`password` VARCHAR( 255 ) NOT NULL ,
PRIMARY KEY (  `id` )
);
  • you need to tell hibernate what class maps to which table, you can achieve this using POJO class, as follows:
package com.dwairi.example.hibernate.model;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;
import org.hibernate.Session;
import com.dwairi.example.hibernate.HibernateUtil;
 
@Entity
@Table(name="users")
public class User {
 public void save(){
  Session session = HibernateUtil.getSessionfactory().getCurrentSession();
  session.getTransaction().begin();
  session.save(this);
 }
 
 @Id
 @GeneratedValue
 private Integer id;
 @Column(name="username")
 private String userName;
 
 @Column(name="password")
 private String password;
 
 public Integer getId() { return id; }
 public void setId(Integer id) { this.id = id; }
 public String getUserName() { return userName; }
 public void setUserName(String userName) { this.userName = userName; }
 public String getPassword() { return password; }
 public void setPassword(String password) { this.password = password; }
}
  • hibernate provide a layer to interact with DBs, that is sessionFactory, that we will be using in this example; it provides a transactional environment and gives you the power of ORM in a simplified way.
    Following is a helper class that will handle creating one sessionFactory object in the course of application life:
package com.dwairi.example.hibernate;
 
import java.io.File;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.dwairi.example.hibernate.model.User;
public class HibernateUtil {
 private static final SessionFactory sessionFactory;
 static {
  try {
   AnnotationConfiguration annotationConfiguration = new AnnotationConfiguration();
   annotationConfiguration.configure(new File("config/hibernate.cfg.xml"));
   annotationConfiguration.addAnnotatedClass(User.class);
   sessionFactory = annotationConfiguration.buildSessionFactory();
  } catch (Throwable ex) {
   System.err.println("Initial SessionFactory creation failed." + ex);
   throw new ExceptionInInitializerError(ex);
  }
 }
 public static SessionFactory getSessionfactory() {
  return sessionFactory;
 }
}
  • as you might noticed, it seems we have used a file hibernate.cfg.xml , what is this? actually, it’s the configuration file for hibernate that will help you configure how to interact with DB using hibernate. here how it will look like
<!--?xml version="1.0" encoding="UTF-8"?-->
 
	  com.mysql.jdbc.Driver
 
	  jdbc:mysql://localhost/example_db
	  root
	  org.hibernate.dialect.MySQLDialect
	  1
	  true
	  true
	  org.hibernate.transaction.JDBCTransactionFactory
	  thread
	  org.hibernate.cache.NoCacheProvider
  • create application runner, I will call it Test.
package com.dwairi.example.hibernate;
import com.dwairi.example.hibernate.model.User;
public class Test {
 public static void main(String[] args) {
 User user = new User();
 user.setUserName("dwairi");
 user.setPassword("password");
 user.save();
 System.out.println("user object saved to DB: " + user.getId());	}
}
  • we will add a log4j.properties file to the root of classpath and turn on debug mode, in order to see what going on, it will look something like this
?View Code PROPERTIES
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

 

Time to see what have we got, run the application, read the debug data logged by hibernate and watch it successfully persists data to DB.

 

Happy DB-hibernate-ing!

code snippet, concepts, Java , , , , ,