src/main/java/ru/indvdum/jpa/dao/JPADataAccessObject.groovy
author indvdum (gotoindvdum[at]gmail[dot]com)
Fri, 24 May 2013 00:01:24 +0400
changeset 23 da78c32e3dcb
parent 21 bba4a82be921
permissions -rw-r--r--
Flush method added
     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.entities.AbstractEntity
    26 import ru.indvdum.jpa.props.Props
    27 
    28 /**
    29  * @author indvdum (gotoindvdum[at]gmail[dot]com)
    30  * @since 08.11.2012 23:35:04
    31  *
    32  */
    33 public class JPADataAccessObject {
    34 
    35 	protected static Logger log = LoggerFactory.getLogger(JPADataAccessObject.class.getSimpleName());
    36 	protected static String persistenceUnitName = null;
    37 	protected static EntityManagerFactory emf = Persistence.createEntityManagerFactory(getPersistenceUnitName(), JPAPropertySelector.select());
    38 	protected EntityManager em = emf.createEntityManager();
    39 	protected EntityTransaction tx = null;
    40 
    41 	JPADataAccessObject() {
    42 		tx = em.getTransaction();
    43 		tx.begin();
    44 	}
    45 
    46 	void close() {
    47 		commit()
    48 		em.close()
    49 		em = null
    50 	}
    51 
    52 	void commit() {
    53 		if(tx != null && tx.isActive()) {
    54 			tx.commit()
    55 		}
    56 	}
    57 
    58 	void rollback() {
    59 		if(tx != null && tx.isActive()) {
    60 			tx.rollback()
    61 		}
    62 	}
    63 
    64 	void detach(Object entity) {
    65 		em.detach(entity);
    66 	}
    67 
    68 	void flush() {
    69 		em.flush();
    70 	}
    71 
    72 	protected static String getPersistenceUnitName() {
    73 		if (persistenceUnitName != null)
    74 			return persistenceUnitName;
    75 
    76 		if (persistenceUnitName == null)
    77 			persistenceUnitName = System.getProperty(Props.PERSISTANCE_UNIT_NAME_PROPERTY);
    78 		if (persistenceUnitName == null) {
    79 			try {
    80 				persistenceUnitName = ResourceBundle.getBundle(Props.JPADAO_PROPERTY_FILE).getString(Props.PERSISTANCE_UNIT_NAME_PROPERTY);
    81 			} catch (MissingResourceException e) {
    82 				log.info("Configuration file " + Props.JPADAO_PROPERTY_FILE + ".properties not found");
    83 			}
    84 		}
    85 		if (persistenceUnitName == null) {
    86 			XMLConfiguration conf = new XMLConfiguration("META-INF/persistence.xml");
    87 			persistenceUnitName = conf.getString("persistence-unit[@name]");
    88 		}
    89 		if (persistenceUnitName == null)
    90 			persistenceUnitName = "database";
    91 		return persistenceUnitName;
    92 	}
    93 
    94 	public static Connection getSQLConnection() throws SQLException {
    95 		OpenJPAEntityManagerFactorySPI openjpaemf = (OpenJPAEntityManagerFactorySPI) OpenJPAPersistence.cast(emf);
    96 		OpenJPAConfiguration conf = openjpaemf.getConfiguration();
    97 		DataSource ds = (DataSource) conf.getConnectionFactory();
    98 		return ds.getConnection();
    99 	}
   100 
   101 	public <T> T mergeAndRefresh(T object) {
   102 		def merged = em.merge(object)
   103 		em.refresh(merged)
   104 
   105 		merged
   106 	}
   107 
   108 	public <T extends AbstractEntity> T read(T object) {
   109 		return find(object.class, object.getIdentifierValue())
   110 	}
   111 
   112 	public <T> T merge(T object) {
   113 		em.merge(object)
   114 	}
   115 
   116 	void refresh(Object ... refreshObjects) {
   117 		for(object in refreshObjects) {
   118 			em.refresh(object)
   119 		}
   120 	}
   121 
   122 	boolean persist(Object ... persistanceQueue) {
   123 		persistAndRemove(persistanceQueue, new Object[0])
   124 	}
   125 
   126 	boolean persist(Collection entities) {
   127 		persistAndRemove(entities.toArray(), new Object[0])
   128 	}
   129 
   130 	boolean remove(Object ... removeQueue) {
   131 		persistAndRemove(new Object[0], removeQueue)
   132 	}
   133 
   134 	boolean remove(Collection entities) {
   135 		persistAndRemove(new Object[0], entities.toArray())
   136 	}
   137 
   138 	synchronized boolean persistAndRemove(Object[] persistanceQueue, Object[] removeQueue) {
   139 
   140 		try {
   141 
   142 			if(persistanceQueue != null) {
   143 				for(object in persistanceQueue) {
   144 					if(object != null) {
   145 						em.persist(object)
   146 					}
   147 				}
   148 			}
   149 
   150 			if(removeQueue != null) {
   151 				for(object in removeQueue) {
   152 					if(object != null) {
   153 						em.remove(object)
   154 					}
   155 				}
   156 			}
   157 		}
   158 		catch(Throwable t) {
   159 			log.error("Error while synchronizing with Database: ", t);
   160 			return false;
   161 		}
   162 
   163 		return true
   164 	}
   165 
   166 	public <T> List<T> list(Class<T> entityClass) {
   167 		// TODO: check for AbstractEntity type of T
   168 		CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(entityClass);
   169 		query.from(entityClass);
   170 		return new ArrayList(em.createQuery(query).getResultList());
   171 	}
   172 
   173 	public <T> List<T> list(Class<T> entityClass, Map<String, Object> equalProperties, Map<String, Object> notEqualProperties) {
   174 		CriteriaBuilder cb = em.getCriteriaBuilder();
   175 		CriteriaQuery<T> query = cb.createQuery(entityClass);
   176 		Root<T> root = query.from(entityClass);
   177 		Collection<Predicate> predicates = new HashSet<Predicate>();
   178 		if(equalProperties != null) {
   179 			for(Entry<String, Object> entry: equalProperties.entrySet()){
   180 				String property = entry.getKey();
   181 				Object value = entry.getValue();
   182 				predicates.add(cb.equal(root.get(property), value));
   183 			}
   184 		}
   185 		if(notEqualProperties != null) {
   186 			for(Entry<String, Object> entry: equalProperties.entrySet()){
   187 				String property = entry.getKey();
   188 				Object value = entry.getValue();
   189 				predicates.add(cb.notEqual(root.get(property), value));
   190 			}
   191 		}
   192 		query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
   193 		return em.createQuery(query).getResultList();
   194 	}
   195 
   196 	public <T> List<T> list(Class<T> entityClass, Object ... equalFieldNamesAndValues) {
   197 		if (equalFieldNamesAndValues.length % 2 != 0)
   198 			throw new RuntimeException("Illegal arguments count: ${equalFieldNamesAndValues.length}");
   199 		Map fieldValues = [:];
   200 		for (int i = 0; i < equalFieldNamesAndValues.length;) {
   201 			String field = (String) equalFieldNamesAndValues[i++];
   202 			Object value = equalFieldNamesAndValues[i++];
   203 			fieldValues["${field}"] = value;
   204 		}
   205 		return list(entityClass, fieldValues, null);
   206 	}
   207 
   208 	public List list(String jpql, Object ... paramValues) {
   209 		Query query = em.createQuery(jpql);
   210 		for (int i = 0; i < paramValues.length; i++)
   211 			query.setParameter(i + 1, paramValues[i]);
   212 		return query.getResultList();
   213 	}
   214 
   215 	public <T> T find(Class<T> entityClass, Object primaryKey) {
   216 		return em.find(entityClass, primaryKey);
   217 	}
   218 
   219 	public <T> T find(Class<T> entityClass, Map<String, Object> equalProperties, Map<String, Object> notEqualProperties) {
   220 		CriteriaBuilder cb = em.getCriteriaBuilder();
   221 		CriteriaQuery<T> query = cb.createQuery(entityClass);
   222 		Root<T> root = query.from(entityClass);
   223 		Collection<Predicate> predicates = new HashSet<Predicate>();
   224 		if(equalProperties != null) {
   225 			for(Entry<String, Object> entry: equalProperties.entrySet()){
   226 				String property = entry.getKey();
   227 				Object value = entry.getValue();
   228 				predicates.add(cb.equal(root.get(property), value));
   229 			}
   230 		}
   231 		if(notEqualProperties != null) {
   232 			for(Entry<String, Object> entry: equalProperties.entrySet()){
   233 				String property = entry.getKey();
   234 				Object value = entry.getValue();
   235 				predicates.add(cb.notEqual(root.get(property), value));
   236 			}
   237 		}
   238 		query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
   239 		T result = null;
   240 		try {
   241 			result = getSingleResult(em.createQuery(query));
   242 		} catch (NoResultException e) {
   243 			log.info("Object not found in Database: " + e.getMessage());
   244 		}
   245 		return result;
   246 	}
   247 
   248 	public <T> T find(Class<T> entityClass, Object ... equalFieldNamesAndValues) {
   249 		if (equalFieldNamesAndValues.length % 2 != 0)
   250 			throw new RuntimeException("Illegal arguments count: ${equalFieldNamesAndValues.length}");
   251 		Map fieldValues = [:];
   252 		for (int i = 0; i < equalFieldNamesAndValues.length;) {
   253 			String field = (String) equalFieldNamesAndValues[i++];
   254 			Object value = equalFieldNamesAndValues[i++];
   255 			fieldValues["${field}"] = value;
   256 		}
   257 		return find(entityClass, fieldValues, null);
   258 	}
   259 
   260 
   261 	public Object find(String jpql, Object ... paramValues) {
   262 		Query query = em.createQuery(jpql);
   263 		for (int i = 0; i < paramValues.length; i++)
   264 			query.setParameter(i + 1, paramValues[i]);
   265 		return getSingleResult(query);
   266 	}
   267 
   268 	public boolean contains(Collection entities) {
   269 		boolean res = true;
   270 		entities.each {res &= contains(it)}
   271 		return res
   272 	}
   273 
   274 	public boolean contains(Object entity) {
   275 		return em.contains(entity);
   276 	}
   277 
   278 	private Object getSingleResult(Query query) {
   279 		try {
   280 			return query.getSingleResult()
   281 		}
   282 		catch (NoResultException e) {
   283 			return null
   284 		}
   285 	}
   286 }