src/main/java/ru/indvdum/jpa/dao/JPADataAccessObject.groovy
author indvdum (gotoindvdum[at]gmail[dot]com)
Wed, 14 Nov 2012 04:11:56 +0400
changeset 11 85972c87bea4
parent 9 dc42467eb5dc
child 13 bfcb605c25ef
permissions -rw-r--r--
Shiro integration completed
     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 	protected static String getPersistenceUnitName() {
    64 		if (persistenceUnitName != null)
    65 			return persistenceUnitName;
    66 
    67 		if (persistenceUnitName == null)
    68 			persistenceUnitName = System.getProperty(Props.PERSISTANCE_UNIT_NAME_PROPERTY);
    69 		if (persistenceUnitName == null) {
    70 			try {
    71 				persistenceUnitName = ResourceBundle.getBundle(Props.JPADAO_PROPERTY_FILE).getString(Props.PERSISTANCE_UNIT_NAME_PROPERTY);
    72 			} catch (MissingResourceException e) {
    73 				log.info("Configuration file " + Props.JPADAO_PROPERTY_FILE + ".properties not found");
    74 			}
    75 		}
    76 		if (persistenceUnitName == null) {
    77 			XMLConfiguration conf = new XMLConfiguration("META-INF/persistence.xml");
    78 			persistenceUnitName = conf.getString("persistence-unit[@name]");
    79 		}
    80 		if (persistenceUnitName == null)
    81 			persistenceUnitName = "database";
    82 		return persistenceUnitName;
    83 	}
    84 
    85 	public static Connection getSQLConnection() throws SQLException {
    86 		OpenJPAEntityManagerFactorySPI openjpaemf = (OpenJPAEntityManagerFactorySPI) OpenJPAPersistence.cast(emf);
    87 		OpenJPAConfiguration conf = openjpaemf.getConfiguration();
    88 		DataSource ds = (DataSource) conf.getConnectionFactory();
    89 		return ds.getConnection();
    90 	}
    91 
    92 	public <T> T mergeAndRefresh(T object) {
    93 		def merged = em.merge(object)
    94 		em.refresh(merged)
    95 
    96 		merged
    97 	}
    98 
    99 	public <T> T merge(T object) {
   100 		em.merge(object)
   101 	}
   102 
   103 	void refresh(Object ... refreshObjects) {
   104 		for(object in refreshObjects) {
   105 			em.refresh(object)
   106 		}
   107 	}
   108 
   109 	boolean persist(Object ... persistanceQueue) {
   110 		persistAndRemove(persistanceQueue, new Object[0])
   111 	}
   112 
   113 	boolean persist(Collection entities) {
   114 		persistAndRemove(entities.toArray(), new Object[0])
   115 	}
   116 
   117 	boolean remove(Object ... removeQueue) {
   118 		persistAndRemove(new Object[0], removeQueue)
   119 	}
   120 
   121 	boolean remove(Collection entities) {
   122 		persistAndRemove(new Object[0], entities.toArray())
   123 	}
   124 
   125 	synchronized boolean persistAndRemove(Object[] persistanceQueue, Object[] removeQueue) {
   126 
   127 		try {
   128 
   129 			if(persistanceQueue != null) {
   130 				for(object in persistanceQueue) {
   131 					if(object != null) {
   132 						em.persist(object)
   133 					}
   134 				}
   135 			}
   136 
   137 			if(removeQueue != null) {
   138 				for(object in removeQueue) {
   139 					if(object != null) {
   140 						em.remove(object)
   141 					}
   142 				}
   143 			}
   144 		}
   145 		catch(Throwable t) {
   146 			log.error("Error while synchronizing with Database: ", t);
   147 			return false;
   148 		}
   149 
   150 		return true
   151 	}
   152 
   153 	public <T> T find(Class<T> entityClass, Object primaryKey) {
   154 		return em.find(entityClass, primaryKey);
   155 	}
   156 
   157 	public <T> List<T> list(Class<T> entityClass, Map<String, Object> equalProperties, Map<String, Object> notEqualProperties) {
   158 		CriteriaBuilder cb = em.getCriteriaBuilder();
   159 		CriteriaQuery<T> query = cb.createQuery(entityClass);
   160 		Root<T> root = query.from(entityClass);
   161 		Collection<Predicate> predicates = new HashSet<Predicate>();
   162 		if(equalProperties != null) {
   163 			for(Entry<String, Object> entry: equalProperties.entrySet()){
   164 				String property = entry.getKey();
   165 				Object value = entry.getValue();
   166 				predicates.add(cb.equal(root.get(property), value));
   167 			}
   168 		}
   169 		if(notEqualProperties != null) {
   170 			for(Entry<String, Object> entry: equalProperties.entrySet()){
   171 				String property = entry.getKey();
   172 				Object value = entry.getValue();
   173 				predicates.add(cb.notEqual(root.get(property), value));
   174 			}
   175 		}
   176 		query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
   177 		return em.createQuery(query).getResultList();
   178 	}
   179 
   180 	public <T> T find(Class<T> entityClass, Map<String, Object> equalProperties, Map<String, Object> notEqualProperties) {
   181 		CriteriaBuilder cb = em.getCriteriaBuilder();
   182 		CriteriaQuery<T> query = cb.createQuery(entityClass);
   183 		Root<T> root = query.from(entityClass);
   184 		Collection<Predicate> predicates = new HashSet<Predicate>();
   185 		if(equalProperties != null) {
   186 			for(Entry<String, Object> entry: equalProperties.entrySet()){
   187 				String property = entry.getKey();
   188 				Object value = entry.getValue();
   189 				predicates.add(cb.equal(root.get(property), value));
   190 			}
   191 		}
   192 		if(notEqualProperties != null) {
   193 			for(Entry<String, Object> entry: equalProperties.entrySet()){
   194 				String property = entry.getKey();
   195 				Object value = entry.getValue();
   196 				predicates.add(cb.notEqual(root.get(property), value));
   197 			}
   198 		}
   199 		query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
   200 		T result = null;
   201 		try {
   202 			result = em.createQuery(query).getSingleResult();
   203 		} catch (NoResultException e) {
   204 			log.info("Object not found in Database: " + e.getMessage());
   205 		}
   206 		return result;
   207 	}
   208 
   209 	public <T> T find(Class<T> entityClass, String field, Object value) {
   210 		return find(entityClass, ["${field}": value], null);
   211 	}
   212 
   213 	public <T> List<T> list(Class<T> entityClass) {
   214 		CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(entityClass);
   215 		query.from(entityClass);
   216 		return new ArrayList(em.createQuery(query).getResultList());
   217 	}
   218 
   219 	public boolean contains(Collection entities) {
   220 		boolean res = true;
   221 		entities.each {res &= contains(it)}
   222 		return res
   223 	}
   224 
   225 	public boolean contains(Object entity) {
   226 		return em.contains(entity);
   227 	}
   228 
   229 	private Object getSingleResult(Query query) {
   230 		try {
   231 			return query.getSingleResult()
   232 		}
   233 		catch (NoResultException e) {
   234 			return null
   235 		}
   236 	}
   237 }