forked from oasp/oasp4j
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AbstractGenericDao.java
395 lines (327 loc) · 11.6 KB
/
AbstractGenericDao.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
package io.oasp.module.jpa.dataaccess.base;
import io.oasp.module.jpa.common.api.to.PaginatedListTo;
import io.oasp.module.jpa.common.api.to.PaginationResultTo;
import io.oasp.module.jpa.common.api.to.PaginationTo;
import io.oasp.module.jpa.common.api.to.SearchCriteriaTo;
import io.oasp.module.jpa.dataaccess.api.GenericDao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.LockModeType;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import net.sf.mmm.util.entity.api.PersistenceEntity;
import net.sf.mmm.util.exception.api.ObjectNotFoundUserException;
import net.sf.mmm.util.search.base.AbstractSearchCriteria;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mysema.query.jpa.impl.JPAQuery;
import com.mysema.query.types.Expression;
/**
* This is the abstract base-implementation of the {@link GenericDao} interface.
*
* @param <ID> is the generic type if the {@link PersistenceEntity#getId() primary key}.
* @param <E> is the generic type of the managed {@link PersistenceEntity}.
*
* @author hohwille
*/
// @Repository
public abstract class AbstractGenericDao<ID, E extends PersistenceEntity<ID>> implements GenericDao<ID, E> {
/** Logger instance. */
private static final Logger LOG = LoggerFactory.getLogger(AbstractGenericDao.class);
private EntityManager entityManager;
/**
* The constructor.
*/
public AbstractGenericDao() {
super();
}
/**
* @return the {@link Class} reflecting the managed entity.
*/
protected abstract Class<E> getEntityClass();
/**
* @return the {@link EntityManager} instance.
*/
protected EntityManager getEntityManager() {
return this.entityManager;
}
/**
* @param entityManager the {@link EntityManager} to inject.
*/
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
/**
* @return the name of the managed entity.
*/
protected String getEntityName() {
return getEntityClass().getSimpleName();
}
/**
* {@inheritDoc}
*/
@Override
public E save(E entity) {
if (isNew(entity)) {
this.entityManager.persist(entity);
LOG.debug("Saved new {} with id {}.", getEntityName(), entity.getId());
return entity;
} else {
if (this.entityManager.find(entity.getClass(), entity.getId()) != null) {
E update = this.entityManager.merge(entity);
LOG.debug("Updated {} with id {}.", getEntityName(), entity.getId());
return update;
} else {
throw new EntityNotFoundException("Entity not found");
}
}
}
/**
* Determines if the given {@link PersistenceEntity} is {@link PersistenceEntity#STATE_NEW new}.
*
* @param entity is the {@link PersistenceEntity} to check.
* @return <code>true</code> if {@link PersistenceEntity#STATE_NEW new}, <code>false</code> otherwise (e.g.
* {@link PersistenceEntity#STATE_DETACHED detached} or {@link PersistenceEntity#STATE_MANAGED managed}.
*/
protected boolean isNew(E entity) {
return entity.getId() == null;
}
/**
* {@inheritDoc}
*/
@Override
public void save(Iterable<? extends E> entities) {
for (E entity : entities) {
save(entity);
}
}
/**
* {@inheritDoc}
*/
@Override
public void forceIncrementModificationCounter(E entity) {
getEntityManager().lock(entity, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
}
/**
* {@inheritDoc}
*/
@Override
public E findOne(ID id) {
E entity = this.entityManager.find(getEntityClass(), id);
return entity;
}
/**
* {@inheritDoc}
*/
@Override
public E find(ID id) throws ObjectNotFoundUserException {
E entity = findOne(id);
if (entity == null) {
throw new ObjectNotFoundUserException(getEntityClass().getSimpleName(), id);
}
return entity;
}
/**
* {@inheritDoc}
*/
@Override
public boolean exists(ID id) {
// pointless...
return findOne(id) != null;
}
/**
* @return an {@link Iterable} to find ALL {@link #getEntityClass() managed entities} from the persistent store. Not
* exposed to API by default as this might not make sense for all kind of entities.
*/
protected List<E> findAll() {
CriteriaQuery<E> query = this.entityManager.getCriteriaBuilder().createQuery(getEntityClass());
Root<E> root = query.from(getEntityClass());
query.select(root);
TypedQuery<E> typedQuery = this.entityManager.createQuery(query);
List<E> resultList = typedQuery.getResultList();
LOG.debug("Query for all {} objects returned {} hit(s).", getEntityName(), resultList.size());
return resultList;
}
/**
* {@inheritDoc}
*/
@Override
public List<E> findAll(Iterable<ID> ids) {
CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
CriteriaQuery<E> query = builder.createQuery(getEntityClass());
Root<E> root = query.from(getEntityClass());
query.select(root);
query.where(root.get("id").in(ids));
TypedQuery<E> typedQuery = this.entityManager.createQuery(query);
List<E> resultList = typedQuery.getResultList();
LOG.debug("Query for selection of {} objects returned {} hit(s).", getEntityName(), resultList.size());
return resultList;
}
/**
* {@inheritDoc}
*/
@Override
public void delete(ID id) {
E entity = this.entityManager.getReference(getEntityClass(), id);
this.entityManager.remove(entity);
LOG.debug("Deleted {} with ID {}.", getEntityName(), id);
}
/**
* {@inheritDoc}
*/
@Override
public void delete(E entity) {
// entity might be detached and could cause trouble in entityManager on remove
if (this.entityManager.contains(entity)) {
this.entityManager.remove(entity);
LOG.debug("Deleted {} with ID {}.", getEntityName(), entity.getId());
} else {
delete(entity.getId());
}
}
/**
* {@inheritDoc}
*/
@Override
public void delete(Iterable<? extends E> entities) {
for (E entity : entities) {
delete(entity);
}
}
@SuppressWarnings("javadoc")
protected PaginatedListTo<E> findPaginated(SearchCriteriaTo criteria, Query query, Expression<E> expr) {
throw new UnsupportedOperationException("Pagination is not yet supported for generic JPA queries.");
}
/**
* Returns a paginated list of entities according to the supplied {@link SearchCriteriaTo criteria}.
* <p>
* Applies {@code limit} and {@code offset} values to the supplied {@query} according to the supplied
* {@link PaginationTo pagination} information inside {@code criteria}.
* <p>
* If a {@link PaginationTo#isTotal() total count} of available entities is requested, will also execute a second
* query, without pagination parameters applied, to obtain said count.
* <p>
* Will install a query timeout if {@link SearchCriteriaTo#getSearchTimeout()} is not null.
*
* @param criteria contains information about the requested page.
* @param query is a query which is preconfigured with the desired conditions for the search.
* @param expr is used for the final mapping from the SQL result to the entities.
* @return a paginated list.
*/
protected PaginatedListTo<E> findPaginated(SearchCriteriaTo criteria, JPAQuery query, Expression<E> expr) {
applyCriteria(criteria, query);
PaginationTo pagination = criteria.getPagination();
PaginationResultTo paginationResult = createPaginationResult(pagination, query);
applyPagination(pagination, query);
List<E> paginatedList = query.list(expr);
return new PaginatedListTo<>(paginatedList, paginationResult);
}
/**
* Creates a {@link PaginationResultTo pagination result} for the given {@code pagination} and {@code query}.
* <p>
* Needs to be called before pagination is applied to the {@code query}.
*
* @param pagination contains information about the requested page.
* @param query is a query preconfigured with the desired conditions for the search.
* @return information about the applied pagination.
*/
protected PaginationResultTo createPaginationResult(PaginationTo pagination, JPAQuery query) {
Long total = calculateTotalBeforePagination(pagination, query);
return new PaginationResultTo(pagination, total);
}
/**
* Calculates the total number of entities the given {@link JPAQuery query} would return without pagination applied.
* <p>
* Needs to be called before pagination is applied to the {@code query}.
*
* @param pagination is the pagination information as requested by the client.
* @param query is the {@link JPAQuery query} for which to calculate the total.
* @return the total count, or {@literal null} if {@link PaginationTo#isTotal()} is {@literal false}.
*/
protected Long calculateTotalBeforePagination(PaginationTo pagination, JPAQuery query) {
Long total = null;
if (pagination.isTotal()) {
total = query.clone().count();
} else {
total = null;
}
return total;
}
/**
* Applies the {@link PaginationTo pagination criteria} to the given {@link JPAQuery}.
*
* @param pagination is the {@link PaginationTo pagination criteria} to apply.
* @param query is the {@link JPAQuery} to apply to.
*/
protected void applyPagination(PaginationTo pagination, JPAQuery query) {
if (pagination == PaginationTo.NO_PAGINATION) {
return;
}
Integer limit = pagination.getSize();
if (limit != null) {
query.limit(limit);
int page = pagination.getPage();
if (page > 0) {
query.offset((page - 1) * limit);
}
}
}
/**
* Applies the meta-data of the given {@link AbstractSearchCriteria search criteria} to the given {@link JPAQuery}.
*
* @param criteria is the {@link AbstractSearchCriteria search criteria} to apply.
* @param query is the {@link JPAQuery} to apply to.
*/
protected void applyCriteria(AbstractSearchCriteria criteria, JPAQuery query) {
Integer limit = criteria.getMaximumHitCount();
if (limit != null) {
query.limit(limit);
}
int offset = criteria.getHitOffset();
if (offset > 0) {
query.offset(offset);
}
Long timeout = criteria.getSearchTimeout();
if (timeout != null) {
query.setHint("javax.persistence.query.timeout", timeout.intValue());
}
}
/**
* Applies the meta-data of the given {@link AbstractSearchCriteria search criteria} to the given {@link Query}.
*
* @param criteria is the {@link AbstractSearchCriteria search criteria} to apply.
* @param query is the {@link Query} to apply to.
*/
protected void applyCriteria(AbstractSearchCriteria criteria, Query query) {
Integer limit = criteria.getMaximumHitCount();
if (limit != null) {
query.setMaxResults(limit);
}
int offset = criteria.getHitOffset();
if (offset > 0) {
query.setFirstResult(offset);
}
Long timeout = criteria.getSearchTimeout();
if (timeout != null) {
query.setHint("javax.persistence.query.timeout", timeout.intValue());
}
}
/**
* Applies the meta-data of the given {@link SearchCriteriaTo search criteria} to the given {@link Query}.
*
* @param criteria is the {@link AbstractSearchCriteria search criteria} to apply.
* @param query is the {@link JPAQuery} to apply to.
*/
protected void applyCriteria(SearchCriteriaTo criteria, JPAQuery query) {
Integer timeout = criteria.getSearchTimeout();
if (timeout != null) {
query.setHint("javax.persistence.query.timeout", timeout.intValue());
}
}
}