Major changes to the cdmlib default term loading and initialization, plus free-text...
[cdmlib.git] / cdmlib-persistence / src / main / java / eu / etaxonomy / cdm / persistence / dao / hibernate / common / CdmEntityDaoBase.java
1 /**
2 * Copyright (C) 2007 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
5 *
6 * The contents of this file are subject to the Mozilla Public License Version 1.1
7 * See LICENSE.TXT at the top of this package for the full license terms.
8 */
9
10 package eu.etaxonomy.cdm.persistence.dao.hibernate.common;
11
12 import java.util.Collection;
13 import java.util.HashMap;
14 import java.util.Iterator;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.UUID;
18
19 import org.apache.log4j.Logger;
20 import org.hibernate.Criteria;
21 import org.hibernate.HibernateException;
22 import org.hibernate.NonUniqueObjectException;
23 import org.hibernate.Query;
24 import org.hibernate.Session;
25 import org.hibernate.criterion.Order;
26 import org.hibernate.criterion.Projections;
27 import org.hibernate.criterion.Restrictions;
28 import org.springframework.dao.DataAccessException;
29 import org.springframework.stereotype.Repository;
30 import org.springframework.transaction.annotation.Transactional;
31
32 import eu.etaxonomy.cdm.model.common.CdmBase;
33 import eu.etaxonomy.cdm.persistence.dao.common.ICdmEntityDao;
34
35
36 /**
37 * @author a.mueller
38 *
39 */
40 @Repository
41 public abstract class CdmEntityDaoBase<T extends CdmBase> extends DaoBase implements ICdmEntityDao<T> {
42 private static final Logger logger = Logger.getLogger(CdmEntityDaoBase.class);
43
44 int flushAfterNo = 2000;
45 protected Class<T> type;
46
47 public CdmEntityDaoBase(Class<T> type){
48 this.type = type;
49 logger.debug("Creating DAO of type [" + type.getSimpleName() + "]");
50 }
51
52 public UUID saveCdmObj(CdmBase cdmObj) throws DataAccessException {
53 getSession().saveOrUpdate(cdmObj);
54 return cdmObj.getUuid();
55 }
56
57 //TODO: Replace saveCdmObj() by saveCdmObject_
58 private UUID saveCdmObject_(T cdmObj){
59 getSession().saveOrUpdate(cdmObj);
60 return cdmObj.getUuid();
61 }
62
63 //TODO: Use everywhere CdmEntityDaoBase.saveAll() instead of ServiceBase.saveCdmObjectAll()?
64 public Map<UUID, T> saveAll(Collection<T> cdmObjCollection){
65 int types = cdmObjCollection.getClass().getTypeParameters().length;
66 if (types > 0){
67 if (logger.isDebugEnabled()){logger.debug("ClassType: + " + cdmObjCollection.getClass().getTypeParameters()[0]);}
68 }
69
70 Map<UUID, T> resultMap = new HashMap<UUID, T>();
71 Iterator<T> iterator = cdmObjCollection.iterator();
72 int i = 0;
73 while(iterator.hasNext()){
74 if ( ( (i % 5000) == 0) && (i > 0) ){logger.debug("Saved " + i + " objects" );}
75 T cdmObj = iterator.next();
76 UUID uuid = saveCdmObject_(cdmObj);
77 if (logger.isDebugEnabled()){logger.debug("Save cdmObj: " + (cdmObj == null? null: cdmObj.toString()));}
78 resultMap.put(uuid, cdmObj);
79 i++;
80 if ( (i % flushAfterNo) == 0){
81 try{
82 logger.debug("flush");
83 flush();
84 }catch(Exception e){
85 logger.error("UUUIIIII");
86 e.printStackTrace();
87 }
88 }
89 }
90
91 if ( logger.isInfoEnabled() ){logger.info("Saved " + i + " objects" );}
92 return resultMap;
93 }
94
95
96 public UUID saveOrUpdate(T transientObject) throws DataAccessException {
97 try {
98 if (logger.isDebugEnabled()){logger.debug("dao saveOrUpdate start...");}
99 if (logger.isDebugEnabled()){logger.debug("transientObject(" + transientObject.getClass().getSimpleName() + ") ID:" + transientObject.getId() + ", UUID: " + transientObject.getUuid()) ;}
100 Session session = getSession();
101 session.saveOrUpdate(transientObject);
102 if (logger.isDebugEnabled()){logger.debug("dao saveOrUpdate end");}
103 return transientObject.getUuid();
104 } catch (NonUniqueObjectException e) {
105 logger.error("Error when in CdmEntityDaoBase saveOrUpdate(obj");
106 logger.error(e.getIdentifier());
107 logger.error(e.getEntityName());
108 logger.error(e.getMessage());
109 e.printStackTrace();
110 throw e;
111 } catch (HibernateException e) {
112
113 e.printStackTrace();
114 throw e;
115 }
116 }
117
118 public UUID save(T newInstance) throws DataAccessException {
119 getSession().save(newInstance);
120 return newInstance.getUuid();
121 }
122
123 public UUID update(T transientObject) throws DataAccessException {
124 getSession().update(transientObject);
125 return transientObject.getUuid();
126 }
127
128 public UUID delete(T persistentObject) throws DataAccessException {
129 getSession().delete(persistentObject);
130 return persistentObject.getUuid();
131 }
132
133 public T findById(int id) throws DataAccessException {
134 return (T) getSession().get(type, id);
135 }
136
137 public T findByUuid(UUID uuid) throws DataAccessException{
138 Session session = getSession();
139 Criteria crit = session.createCriteria(type);
140 crit.add(Restrictions.eq("uuid", uuid));
141 crit.addOrder(Order.desc("created"));
142 List<T> results = crit.list();
143 if (results.isEmpty()){
144 return null;
145 }else{
146 return results.get(0);
147 }
148 }
149
150 public Boolean exists(UUID uuid) {
151 if (findByUuid(uuid)==null){
152 return false;
153 }
154 return true;
155 }
156
157 public int count() {
158 return count(type);
159 }
160
161 public <TYPE extends T> int count(Class<TYPE> type) {
162 Session session = getSession();
163 Criteria crit = session.createCriteria(type);
164 crit.setProjection(Projections.projectionList().add(Projections.rowCount()));
165 Integer nbrRows = (Integer) crit.uniqueResult();
166 return nbrRows.intValue();
167 }
168
169 public List<T> list(Integer limit, Integer start) {
170 Criteria crit = getSession().createCriteria(type);
171 if(limit != null) {
172 crit.setFirstResult(start);
173 crit.setMaxResults(limit);
174 }
175 return crit.list();
176 }
177
178 public <TYPE extends T> List<TYPE> list(Class<TYPE> type, Integer limit, Integer start) {
179 Criteria crit = getSession().createCriteria(type);
180 if(limit != null) {
181 crit.setFirstResult(start);
182 crit.setMaxResults(limit);
183 }
184 return crit.list();
185 }
186
187
188 public List<T> rows(String tableName, int limit, int start) {
189 Query query = getSession().createQuery("from " + tableName + " order by uuid");
190 query.setFirstResult(start);
191 query.setMaxResults(limit);
192 List<T> result = query.list();
193 return result;
194 }
195 }