Friday, September 22, 2017

Simple code to connect to database using hibernate (annotations) and maven

In this paper we will try to write a mavenized java application that will connect to an Oracle database and perform some data manipulation.

First of all, why maven ?
If you have the right jar dependencies whithout maven that's great ! no need to use maven... Personally i've faced a big problem to download and put the correct dependencies (no only packages but versions also!) together into my project.

Then let's talk maven !

1- Create the application with maven


Run this command line :

mvn archetype:generate -DgroupId=com.itillusion.migrators -DartifactId=loader -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false


2- Add dependencies to POM

 
 
     org.hibernate
     hibernate-core
     5.2.11.Final
 
 
 
     org.hibernate
     hibernate-tools
     3.2.0.ga
 

And that's all, no need to other dependencies ...
So our new pom.xml become :

 

  4.0.0
  com.itillusion.migrators
  loader
  jar
  1.0-SNAPSHOT
  loader
  http://maven.apache.org
  
    
      junit
      junit
      3.8.1
      test
    
    
    
 
     org.hibernate
     hibernate-core
     5.2.11.Final
 
 
     org.hibernate
     hibernate-tools
     3.2.0.ga
 
     
  


Note that here we use hibernate 5.2.11

3- Build the HibernateUtils class

This class is recommended, it is a Singleton design pattern implementation, and will facilitate our work

 
package com.itillusion.migrators.utils;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import tn.cnss.referentiel.models.Assure;
import tn.cnss.referentiel.models.Beneficiaire;


public class HibernateUtils {
 private static final SessionFactory sessionFactory;



 static {
  try {
  StandardServiceRegistry standardRegistry = 
  new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
  
  //Annotated  classes to be scanned
  List> classes = new ArrayList>();
  classes.add(Assure.class);
  classes.add(Beneficiaire.class);
  
  //Attach classes 
  MetadataSources metadataSources = new MetadataSources(standardRegistry);
  for (Class annotatedClass : classes) {
      metadataSources.addAnnotatedClass(annotatedClass);
  }

  sessionFactory = metadataSources.buildMetadata()
      .buildSessionFactory();

  } catch (Throwable th) {

   System.err.println("Enitial SessionFactory creation failed" + th);
   throw new ExceptionInInitializerError(th);

  }
 }
 public static SessionFactory getSessionFactory() {

  return sessionFactory;

 }
 public static Session getSession() throws org.hibernate.HibernateException {
     SessionFactory sessionFactory = HibernateUtils.getSessionFactory();
     Session sess = null;       
     try {         
         sess = sessionFactory.getCurrentSession();  
     } catch (org.hibernate.HibernateException he) {  
         sess = sessionFactory.openSession();     
     }             
     return sess;
  } 
}
Note in the fragment
 
  classes.add(Assure.class);
  classes.add(Beneficiaire.class);

We have added our annotated classes !
I'm sure that there is a more elegant methods to do this, (iteration on packages using java reflection api) but in my case i just need two tabled to map.

Note also that we conserved our classic hibernate.cfg.xml file. (Surely we can avoid that and use100% java code to confgiure hibernate, but i don't recommand that and it is more logic to store database informations in a separate faile that can change independently from our code)

Here is a simple cfg file:
 



    
        oracle.jdbc.driver.OracleDriver
        PASSWORD
        jdbc:oracle:thin:@xxx.yy.zz.tt:SID
        USERNAME
        DEFAULT_SCHEMA 
        org.hibernate.dialect.Oracle10gDialect
    


to be continued

No comments:

Post a Comment