Thursday, February 7, 2013

Generic Methods in Java


One day I was working with JPA, however I noticed that I had to repeat the process of creating an EntityManagerFactory and EntityManager object in all the DAO (Data Access Object) classes. There after, I had to open begin and commit a transaction every time I had to save and or update the object.

Due to repetition of such code, I become bold.

Certainly I thought it would be better to centralize all the JPA 'boiler' code in one class with the use of generic methods.

When using JPA, to obtain an entity, one has to call find method on the EntityManager  as shown below

entityManager.find(MyClass.lass,keyFieldValue) ;

To avoid passing the 'concrete' class, I had to create a generic method for find method in my utility class as shown below

public <T> T find(Class<T> entity, Object param){
  EntityManager em=entityManagerFactory.createEntityManager();
  try{
   return em.find(entity,param);
  }finally{
   if(em.isOpen()){
    em.close();
   }
  }
 }

Therefore, I would reuse the method without worry of casting problems, as it would be if I had used and Object class. Below is a complete complete class

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

public class JpaUtil {
 
 private EntityManagerFactory entityManagerFactory;
 
 public JpaUtil(){
  entityManagerFactory=Persistence.createEntityManagerFactory("yourPersistenceUnitName");
 }
 public void persist(Object entity){
  EntityManager em=entityManagerFactory.createEntityManager();
  try{
   em.getTransaction().begin();
   em.persist(entity);
   em.getTransaction().commit();
  }finally{
   if(em.isOpen()){
    em.close();
   }
  }
 }
 
 
 public void update(Object entity){
  EntityManager em=entityManagerFactory.createEntityManager();
  try{
   em.getTransaction().begin();
   em.merge(entity);
   em.getTransaction().commit();
  }finally{
   if(em.isOpen()){
    em.close();
   }
  }
 }
 
 public void delete(Object entity){
  EntityManager em=entityManagerFactory.createEntityManager();
  try{
   em.getTransaction().begin();
   em.remove(entity);
   em.getTransaction().commit();
  }finally{
   if(em.isOpen()){
    em.close();
   }
  }
 }
 
 public <T> T find(Class<T> entity, Object param){
  EntityManager em=entityManagerFactory.createEntityManager();
  try{
   return em.find(entity,param);
  }finally{
   if(em.isOpen()){
    em.close();
   }
  }
 }
  
 @SuppressWarnings("unchecked")
 public <T> T getSingleResult(String sql,Class<T> clazz){
  EntityManager em=entityManagerFactory.createEntityManager();
  try{
   Query query=em.createNativeQuery(sql,clazz);
   return (T)query.getSingleResult();
  }finally{
   if(em.isOpen()){
    em.close();
   }
  }
 }
 
 @SuppressWarnings("unchecked")
 public <T> T getSingleResult(String sql,List<Object> params,Class<T> clazz){
  EntityManager em=entityManagerFactory.createEntityManager();
  try{
   Query query=em.createNativeQuery(sql,clazz);
   
   if(params!=null){
    for(int i=0; i<params.size();i++){
     query.setParameter(i+1, params.get(i));
    }
   }
   return (T)query.getSingleResult();
  }finally{
   if(em.isOpen()){
    em.close();
   }
  }
 }
 
 @SuppressWarnings("unchecked")
 public <T> List<T> getResultList(String sql,Class<T> clazz){
  EntityManager em=entityManagerFactory.createEntityManager();
  try{
   Query query=em.createNativeQuery(sql,clazz);
   return (List<T>)query.getResultList();
  }finally{
   if(em.isOpen()){
    em.close();
   }
  }
 }
 

 @SuppressWarnings("unchecked")
 public <T> List<T> getResultList(String sql,List<Object> params,Class<T> clazz){
  EntityManager em=entityManagerFactory.createEntityManager();
  try{
   Query query=em.createNativeQuery(sql,clazz);
  
   if(params!=null){
    for(int i=0; i<params.size();i++){
     query.setParameter(i+1, params.get(i));
    }
   }
   return (List<T>)query.getResultList();
  }finally{
   if(em.isOpen()){
    em.close();
   }
  }
 }
}

I hope the above information was helpful. Be free to think how you may utilize the similar approach in your projects. ;)

Saturday, February 4, 2012

Java 7 - Binary Literals

Java 7 enables developers to 'create' and assign binary values to integral types (byte, short, int, and long) . Binary values starts with 0b or 0B followed by and combination of 0s and 1s. For instance

0b1111 is equivalent to 15.

You can perform arithmetic operations as well as comparisons. Below is the code which demonstrates the use of binary literals

package com.benjmaz.literals;
/***
 * 
 * @author Ben Mazyopa
 * The purpose of this code is to illustrate the use of binary strings
 */
public class BinaryLiterals {

 /**
  * @param args
  */
 public static void main(String[] args) {
  //assigns 15 to x
  int a=0b1111;
  //assigns a values decimal
  int b=15;
  long c=a;
  float d=-0b100111;
  
  // A 64-bit 'long' value. Note the "L" suffix:
  double e= 0b1010000101000101101000010100010110100001010001011010000101000101L;
  // A 64-bit 'long' value. Note the "L" suffix:
  long f = 0b1010000101000101101000010100010110100001010001011010000101000101L;
  
  //adds 15 + 15 and stores to ans
  int ans =a+b;
  //prints 30 = 15 + 15
  System.out.format("%d = %d + %d%n",ans,a,b);
  //prints true = 15 == 15
  System.out.format("%s = %d == %d%n",c==a,c,a);
  //prints d = -39.0
  System.out.println("d = " + d );
  System.out.println("e = " + e );
  System.out.println("f = " + f );
 }
}

The above code will output the following

30 = 15 + 15
true = 15 == 15
d = -39.0
e = -6.8258723397796086E18
f = -6825872339779608251

For more information consult oracle technotes