Advertisement
ballchaichana

StandardDAOImpl

Aug 20th, 2018
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.66 KB | None | 0 0
  1. package th.athichitsakul.dao.impl;
  2.  
  3. import java.lang.reflect.ParameterizedType;
  4. import java.util.List;
  5.  
  6. import th.athichitsakul.dao.DAO;
  7. import th.athichitsakul.dao.StandardDAO;
  8.  
  9. public abstract class StandardDAOImpl<T> implements StandardDAO<T>{
  10.     Class<T> objectClass;
  11.     protected DAO DAO = null;
  12.     public StandardDAOImpl(String puID)  {
  13.         this.DAO = new DAO(puID);
  14.         objectClass = (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
  15.     }
  16.     public void save(T object)throws Exception{
  17.         try{
  18.             DAO.begin();
  19.             DAO.save(object);
  20.         }catch(Exception e){
  21.            
  22.             if (DAO.getTransaction().isActive()) {
  23.                 DAO.getTransaction().rollback();
  24.             }
  25.             throw e;
  26.         }finally{
  27.             DAO.close();
  28.         }
  29.     }
  30.     public void remove(Object primaryKey)throws Exception{
  31.         try{
  32.             DAO.begin();
  33.             Object object = DAO.getEntityManager().find(objectClass, primaryKey);
  34.             if(object==null) throw new NullPointerException("Removing Object Not Found");
  35.             DAO.getEntityManager().remove(object);
  36.         }catch(Exception e){
  37.             throw e;
  38.         }finally{
  39.             DAO.close();
  40.         }
  41.     }
  42.     public T find(Object primaryKey) throws Exception{
  43.         T queryResult = null;
  44.         try{
  45.             DAO.begin();
  46.             queryResult = DAO.getEntityManager().find(objectClass, primaryKey);
  47.         }catch(Exception e){
  48.             throw e;
  49.         }finally{
  50.             DAO.close();
  51.         }
  52.         return queryResult;
  53.     }
  54.     public List<T> list() throws Exception{
  55.         List<T> queryResult = null;
  56.         try{
  57.             DAO.begin();
  58.             queryResult = DAO.getEntityManager().createQuery("FROM ".concat(objectClass.getName() )).getResultList();
  59.         }catch(Exception e){
  60.             throw e;
  61.         }finally{
  62.             DAO.close();
  63.         }
  64.         return queryResult;
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement