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();
39 JPADataAccessObject() {
43 protected static String getPersistenceUnitName() {
44 if (persistenceUnitName != null)
45 return persistenceUnitName;
47 if (persistenceUnitName == null)
48 persistenceUnitName = System.getProperty(Props.PERSISTANCE_UNIT_NAME_PROPERTY);
49 if (persistenceUnitName == null) {
51 persistenceUnitName = ResourceBundle.getBundle(Props.JPADAO_PROPERTY_FILE).getString(Props.PERSISTANCE_UNIT_NAME_PROPERTY);
52 } catch (MissingResourceException e) {
53 log.info("Configuration file " + Props.JPADAO_PROPERTY_FILE + ".properties not found");
56 if (persistenceUnitName == null) {
57 XMLConfiguration conf = new XMLConfiguration("META-INF/persistence.xml");
58 persistenceUnitName = conf.getString("persistence-unit[@name]");
60 if (persistenceUnitName == null)
61 persistenceUnitName = "database";
62 return persistenceUnitName;
65 public static Connection getSQLConnection() throws SQLException {
66 OpenJPAEntityManagerFactorySPI openjpaemf = (OpenJPAEntityManagerFactorySPI) OpenJPAPersistence.cast(emf);
67 OpenJPAConfiguration conf = openjpaemf.getConfiguration();
68 DataSource ds = (DataSource) conf.getConnectionFactory();
69 return ds.getConnection();
77 public <T> T mergeAndRefresh(T object) {
78 def merged = em.merge(object)
84 public <T> T merge(T object) {
88 void refresh(Object ... refreshObjects) {
89 for(object in refreshObjects) {
94 boolean persist(Object ... persistanceQueue) {
95 persistAndRemove(persistanceQueue, new Object[0])
98 boolean persist(Collection entities) {
99 persistAndRemove(entities.toArray(), new Object[0])
102 boolean remove(Object ... removeQueue) {
103 persistAndRemove(new Object[0], removeQueue)
106 boolean remove(Collection entities) {
107 persistAndRemove(new Object[0], entities.toArray())
110 synchronized boolean persistAndRemove(Object[] persistanceQueue, Object[] removeQueue) {
111 EntityTransaction tx = null
114 tx = em.getTransaction()
117 if(persistanceQueue != null) {
118 for(object in persistanceQueue) {
125 if(removeQueue != null) {
126 for(object in removeQueue) {
136 log.error("Error while synchronizing with Database: ", t);
138 if(tx != null && tx.isActive()) {
148 public <T> T find(Class<T> entityClass, Object primaryKey) {
149 return em.find(entityClass, primaryKey);
152 public <T> List<T> list(Class<T> entityClass, Map<String, Object> equalProperties, Map<String, Object> notEqualProperties) {
153 CriteriaBuilder cb = em.getCriteriaBuilder();
154 CriteriaQuery<T> query = cb.createQuery(entityClass);
155 Root<T> root = query.from(entityClass);
156 Collection<Predicate> predicates = new HashSet<Predicate>();
157 if(equalProperties != null) {
158 for(Entry<String, Object> entry: equalProperties.entrySet()){
159 String property = entry.getKey();
160 Object value = entry.getValue();
161 predicates.add(cb.equal(root.get(property), value));
164 if(notEqualProperties != null) {
165 for(Entry<String, Object> entry: equalProperties.entrySet()){
166 String property = entry.getKey();
167 Object value = entry.getValue();
168 predicates.add(cb.notEqual(root.get(property), value));
171 query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
172 return em.createQuery(query).getResultList();
175 public <T> T find(Class<T> entityClass, Map<String, Object> equalProperties, Map<String, Object> notEqualProperties) {
176 CriteriaBuilder cb = em.getCriteriaBuilder();
177 CriteriaQuery<T> query = cb.createQuery(entityClass);
178 Root<T> root = query.from(entityClass);
179 Collection<Predicate> predicates = new HashSet<Predicate>();
180 if(equalProperties != null) {
181 for(Entry<String, Object> entry: equalProperties.entrySet()){
182 String property = entry.getKey();
183 Object value = entry.getValue();
184 predicates.add(cb.equal(root.get(property), value));
187 if(notEqualProperties != null) {
188 for(Entry<String, Object> entry: equalProperties.entrySet()){
189 String property = entry.getKey();
190 Object value = entry.getValue();
191 predicates.add(cb.notEqual(root.get(property), value));
194 query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
197 result = em.createQuery(query).getSingleResult();
198 } catch (NoResultException e) {
199 log.error("Error while searching object in Database: ", e);
204 public <T> List<T> list(Class<T> entityClass) {
205 CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(entityClass);
206 query.from(entityClass);
207 return new ArrayList(em.createQuery(query).getResultList());
210 public boolean contains(Collection entities) {
212 entities.each {res &= contains(it)}
216 public boolean contains(Object entity) {
217 return em.contains(entity);
220 private Object getSingleResult(Query query) {
222 return query.getSingleResult()
224 catch (NoResultException e) {