src/main/java/ru/indvdum/jpa/dao/JPADataAccessObject.groovy
author indvdum (gotoindvdum[at]gmail[dot]com)
Sat, 24 Nov 2012 15:58:22 +0400
changeset 14 22646fd200c5
parent 13 bfcb605c25ef
child 16 409046072775
permissions -rw-r--r--
Support of auto-generating Enum field types
     1 package ru.indvdum.jpa.dao
     2 import java.sql.Connection
     3 import java.sql.SQLException
     4 import java.util.Map.Entry
     5 
     6 import javax.persistence.EntityManager
     7 import javax.persistence.EntityManagerFactory
     8 import javax.persistence.EntityTransaction
     9 import javax.persistence.NoResultException
    10 import javax.persistence.Persistence
    11 import javax.persistence.Query
    12 import javax.persistence.criteria.CriteriaBuilder
    13 import javax.persistence.criteria.CriteriaQuery
    14 import javax.persistence.criteria.Predicate
    15 import javax.persistence.criteria.Root
    16 import javax.sql.DataSource
    17 
    18 import org.apache.commons.configuration.XMLConfiguration
    19 import org.apache.openjpa.conf.OpenJPAConfiguration
    20 import org.apache.openjpa.persistence.OpenJPAEntityManagerFactorySPI
    21 import org.apache.openjpa.persistence.OpenJPAPersistence
    22 import org.slf4j.Logger
    23 import org.slf4j.LoggerFactory
    24 
    25 import ru.indvdum.jpa.props.Props
    26 
    27 /**
    28  * @author indvdum (gotoindvdum[at]gmail[dot]com)
    29  * @since 08.11.2012 23:35:04
    30  *
    31  */
    32 public class JPADataAccessObject {
    33 
    34 	protected static Logger log = LoggerFactory.getLogger(JPADataAccessObject.class.getSimpleName());
    35 	protected static String persistenceUnitName = null;
    36 	protected static EntityManagerFactory emf = Persistence.createEntityManagerFactory(getPersistenceUnitName(), JPAPropertySelector.select());
    37 	protected EntityManager em = emf.createEntityManager();
    38 	protected EntityTransaction tx = null;
    39 
    40 	JPADataAccessObject() {
    41 		tx = em.getTransaction();
    42 		tx.begin();
    43 	}
    44 
    45 	void close() {
    46 		commit()
    47 		em.close()
    48 		em = null
    49 	}
    50 
    51 	void commit() {
    52 		if(tx != null && tx.isActive()) {
    53 			tx.commit()
    54 		}
    55 	}
    56 
    57 	void rollback() {
    58 		if(tx != null && tx.isActive()) {
    59 			tx.rollback()
    60 		}
    61 	}
    62 	
    63 	void detach(Object entity) {
    64 		em.detach(entity);
    65 	}
    66 
    67 	protected static String getPersistenceUnitName() {
    68 		if (persistenceUnitName != null)
    69 			return persistenceUnitName;
    70 
    71 		if (persistenceUnitName == null)
    72 			persistenceUnitName = System.getProperty(Props.PERSISTANCE_UNIT_NAME_PROPERTY);
    73 		if (persistenceUnitName == null) {
    74 			try {
    75 				persistenceUnitName = ResourceBundle.getBundle(Props.JPADAO_PROPERTY_FILE).getString(Props.PERSISTANCE_UNIT_NAME_PROPERTY);
    76 			} catch (MissingResourceException e) {
    77 				log.info("Configuration file " + Props.JPADAO_PROPERTY_FILE + ".properties not found");
    78 			}
    79 		}
    80 		if (persistenceUnitName == null) {
    81 			XMLConfiguration conf = new XMLConfiguration("META-INF/persistence.xml");
    82 			persistenceUnitName = conf.getString("persistence-unit[@name]");
    83 		}
    84 		if (persistenceUnitName == null)
    85 			persistenceUnitName = "database";
    86 		return persistenceUnitName;
    87 	}
    88 
    89 	public static Connection getSQLConnection() throws SQLException {
    90 		OpenJPAEntityManagerFactorySPI openjpaemf = (OpenJPAEntityManagerFactorySPI) OpenJPAPersistence.cast(emf);
    91 		OpenJPAConfiguration conf = openjpaemf.getConfiguration();
    92 		DataSource ds = (DataSource) conf.getConnectionFactory();
    93 		return ds.getConnection();
    94 	}
    95 
    96 	public <T> T mergeAndRefresh(T object) {
    97 		def merged = em.merge(object)
    98 		em.refresh(merged)
    99 
   100 		merged
   101 	}
   102 
   103 	public <T> T merge(T object) {
   104 		em.merge(object)
   105 	}
   106 
   107 	void refresh(Object ... refreshObjects) {
   108 		for(object in refreshObjects) {
   109 			em.refresh(object)
   110 		}
   111 	}
   112 
   113 	boolean persist(Object ... persistanceQueue) {
   114 		persistAndRemove(persistanceQueue, new Object[0])
   115 	}
   116 
   117 	boolean persist(Collection entities) {
   118 		persistAndRemove(entities.toArray(), new Object[0])
   119 	}
   120 
   121 	boolean remove(Object ... removeQueue) {
   122 		persistAndRemove(new Object[0], removeQueue)
   123 	}
   124 
   125 	boolean remove(Collection entities) {
   126 		persistAndRemove(new Object[0], entities.toArray())
   127 	}
   128 
   129 	synchronized boolean persistAndRemove(Object[] persistanceQueue, Object[] removeQueue) {
   130 
   131 		try {
   132 
   133 			if(persistanceQueue != null) {
   134 				for(object in persistanceQueue) {
   135 					if(object != null) {
   136 						em.persist(object)
   137 					}
   138 				}
   139 			}
   140 
   141 			if(removeQueue != null) {
   142 				for(object in removeQueue) {
   143 					if(object != null) {
   144 						em.remove(object)
   145 					}
   146 				}
   147 			}
   148 		}
   149 		catch(Throwable t) {
   150 			log.error("Error while synchronizing with Database: ", t);
   151 			return false;
   152 		}
   153 
   154 		return true
   155 	}
   156 
   157 	public <T> T find(Class<T> entityClass, Object primaryKey) {
   158 		return em.find(entityClass, primaryKey);
   159 	}
   160 
   161 	public <T> List<T> list(Class<T> entityClass, Map<String, Object> equalProperties, Map<String, Object> notEqualProperties) {
   162 		CriteriaBuilder cb = em.getCriteriaBuilder();
   163 		CriteriaQuery<T> query = cb.createQuery(entityClass);
   164 		Root<T> root = query.from(entityClass);
   165 		Collection<Predicate> predicates = new HashSet<Predicate>();
   166 		if(equalProperties != null) {
   167 			for(Entry<String, Object> entry: equalProperties.entrySet()){
   168 				String property = entry.getKey();
   169 				Object value = entry.getValue();
   170 				predicates.add(cb.equal(root.get(property), value));
   171 			}
   172 		}
   173 		if(notEqualProperties != null) {
   174 			for(Entry<String, Object> entry: equalProperties.entrySet()){
   175 				String property = entry.getKey();
   176 				Object value = entry.getValue();
   177 				predicates.add(cb.notEqual(root.get(property), value));
   178 			}
   179 		}
   180 		query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
   181 		return em.createQuery(query).getResultList();
   182 	}
   183 
   184 	public <T> T find(Class<T> entityClass, Map<String, Object> equalProperties, Map<String, Object> notEqualProperties) {
   185 		CriteriaBuilder cb = em.getCriteriaBuilder();
   186 		CriteriaQuery<T> query = cb.createQuery(entityClass);
   187 		Root<T> root = query.from(entityClass);
   188 		Collection<Predicate> predicates = new HashSet<Predicate>();
   189 		if(equalProperties != null) {
   190 			for(Entry<String, Object> entry: equalProperties.entrySet()){
   191 				String property = entry.getKey();
   192 				Object value = entry.getValue();
   193 				predicates.add(cb.equal(root.get(property), value));
   194 			}
   195 		}
   196 		if(notEqualProperties != null) {
   197 			for(Entry<String, Object> entry: equalProperties.entrySet()){
   198 				String property = entry.getKey();
   199 				Object value = entry.getValue();
   200 				predicates.add(cb.notEqual(root.get(property), value));
   201 			}
   202 		}
   203 		query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
   204 		T result = null;
   205 		try {
   206 			result = em.createQuery(query).getSingleResult();
   207 		} catch (NoResultException e) {
   208 			log.info("Object not found in Database: " + e.getMessage());
   209 		}
   210 		return result;
   211 	}
   212 
   213 	public <T> T find(Class<T> entityClass, String field, Object value) {
   214 		return find(entityClass, ["${field}": value], null);
   215 	}
   216 
   217 	public <T> List<T> list(Class<T> entityClass) {
   218 		CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(entityClass);
   219 		query.from(entityClass);
   220 		return new ArrayList(em.createQuery(query).getResultList());
   221 	}
   222 
   223 	public boolean contains(Collection entities) {
   224 		boolean res = true;
   225 		entities.each {res &= contains(it)}
   226 		return res
   227 	}
   228 
   229 	public boolean contains(Object entity) {
   230 		return em.contains(entity);
   231 	}
   232 
   233 	private Object getSingleResult(Query query) {
   234 		try {
   235 			return query.getSingleResult()
   236 		}
   237 		catch (NoResultException e) {
   238 			return null
   239 		}
   240 	}
   241 }