SHARE
TWEET

DAO

a guest Dec 15th, 2019 69 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package th.athichitsakul.dao;
  2.  
  3. import java.util.HashMap;
  4.  
  5. import javax.persistence.EntityManager;
  6. import javax.persistence.EntityManagerFactory;
  7. import javax.persistence.EntityTransaction;
  8. import javax.persistence.Persistence;
  9.  
  10. public class DAO {
  11.     private static final HashMap<String, EntityManagerFactory> factoryMAP = new HashMap<>();
  12.     private EntityManagerFactory factory;
  13.     private EntityManager entityManager;
  14.     private EntityTransaction transaction;
  15.  
  16.     public DAO(String puID) {
  17.         EntityManagerFactory factory = factoryMAP.get(puID);
  18.         if (factory == null) {
  19.             System.out.println("=== Create new Entity manager factory for : " + puID + "===");
  20.             this.factory = Persistence.createEntityManagerFactory(puID);
  21.             this.init();
  22.             factoryMAP.put(puID, this.factory);
  23.         }else {
  24.             System.out.println("=== Load registerd factory for : " + puID + "===");
  25.             this.factory = factory;
  26.             this.init();
  27.         }
  28.        
  29.     }
  30.     public void emfClose() {
  31.         this.factory.close();
  32.     }
  33.    
  34.     public void init() {
  35.         this.entityManager = this.factory.createEntityManager();
  36.     }
  37.    
  38.     public void begin() {
  39.         if (entityManager==null || !entityManager.isOpen()) {
  40.             entityManager = factory.createEntityManager();
  41.         }
  42.         transaction = entityManager.getTransaction();
  43.         transaction.begin();
  44.     }
  45.     public void close() {
  46.         try{
  47.             transaction.commit();
  48.         }catch (Exception e) {
  49.             // Do nothing, just want to close}
  50.         }
  51.         try{
  52.             entityManager.close();
  53.         }catch (Exception e) {
  54.             // Do nothing, just want to close}
  55.         }
  56.     }
  57.     public EntityManager getEntityManager() {
  58.         if (entityManager==null || !entityManager.isOpen()) {
  59.             entityManager = factory.createEntityManager();
  60.         }
  61.         return entityManager;
  62.     }
  63.     public EntityTransaction getTransaction() {
  64.         return transaction;
  65.     }
  66.     public void clear() {
  67.         entityManager.clear();
  68.     }
  69.     public void save(Object entity) {
  70.         entityManager.persist(entity);
  71.         transaction.commit();
  72.     }
  73. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top