1 package ru.indvdum.jpa.dao
2 import java.sql.Connection
3 import java.sql.SQLException
4 import java.util.Map.Entry
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
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
25 import ru.indvdum.jpa.props.Props
28 * @author indvdum (gotoindvdum[at]gmail[dot]com)
29 * @since 08.11.2012 23:35:04
32 public class JPADataAccessObject {
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;
40 JPADataAccessObject() {
41 tx = em.getTransaction();
52 if(tx != null && tx.isActive()) {
58 if(tx != null && tx.isActive()) {
63 void detach(Object entity) {
67 protected static String getPersistenceUnitName() {
68 if (persistenceUnitName != null)
69 return persistenceUnitName;
71 if (persistenceUnitName == null)
72 persistenceUnitName = System.getProperty(Props.PERSISTANCE_UNIT_NAME_PROPERTY);
73 if (persistenceUnitName == null) {
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");
80 if (persistenceUnitName == null) {
81 XMLConfiguration conf = new XMLConfiguration("META-INF/persistence.xml");
82 persistenceUnitName = conf.getString("persistence-unit[@name]");
84 if (persistenceUnitName == null)
85 persistenceUnitName = "database";
86 return persistenceUnitName;
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();
96 public <T> T mergeAndRefresh(T object) {
97 def merged = em.merge(object)
103 public <T> T merge(T object) {
107 void refresh(Object ... refreshObjects) {
108 for(object in refreshObjects) {
113 boolean persist(Object ... persistanceQueue) {
114 persistAndRemove(persistanceQueue, new Object[0])
117 boolean persist(Collection entities) {
118 persistAndRemove(entities.toArray(), new Object[0])
121 boolean remove(Object ... removeQueue) {
122 persistAndRemove(new Object[0], removeQueue)
125 boolean remove(Collection entities) {
126 persistAndRemove(new Object[0], entities.toArray())
129 synchronized boolean persistAndRemove(Object[] persistanceQueue, Object[] removeQueue) {
133 if(persistanceQueue != null) {
134 for(object in persistanceQueue) {
141 if(removeQueue != null) {
142 for(object in removeQueue) {
150 log.error("Error while synchronizing with Database: ", t);
157 public <T> T find(Class<T> entityClass, Object primaryKey) {
158 return em.find(entityClass, primaryKey);
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));
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));
180 query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
181 return em.createQuery(query).getResultList();
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));
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));
203 query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
206 result = em.createQuery(query).getSingleResult();
207 } catch (NoResultException e) {
208 log.info("Object not found in Database: " + e.getMessage());
213 public <T> T find(Class<T> entityClass, String field, Object value) {
214 return find(entityClass, ["${field}": value], null);
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());
223 public boolean contains(Collection entities) {
225 entities.each {res &= contains(it)}
229 public boolean contains(Object entity) {
230 return em.contains(entity);
233 private Object getSingleResult(Query query) {
235 return query.getSingleResult()
237 catch (NoResultException e) {