2 * Copyright (C) 2007 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
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.
10 package eu
.etaxonomy
.cdm
.persistence
.dao
.hibernate
.common
;
12 import java
.lang
.reflect
.Field
;
13 import java
.util
.ArrayList
;
14 import java
.util
.Collection
;
15 import java
.util
.EnumSet
;
16 import java
.util
.HashMap
;
17 import java
.util
.HashSet
;
18 import java
.util
.Iterator
;
19 import java
.util
.List
;
22 import java
.util
.UUID
;
24 import org
.apache
.logging
.log4j
.LogManager
;import org
.apache
.logging
.log4j
.Logger
;
25 import org
.hibernate
.Criteria
;
26 import org
.hibernate
.FlushMode
;
27 import org
.hibernate
.HibernateException
;
28 import org
.hibernate
.LockOptions
;
29 import org
.hibernate
.NonUniqueObjectException
;
30 import org
.hibernate
.Session
;
31 import org
.hibernate
.criterion
.Criterion
;
32 import org
.hibernate
.criterion
.DetachedCriteria
;
33 import org
.hibernate
.criterion
.Disjunction
;
34 import org
.hibernate
.criterion
.Example
;
35 import org
.hibernate
.criterion
.Example
.PropertySelector
;
36 import org
.hibernate
.criterion
.LogicalExpression
;
37 import org
.hibernate
.criterion
.Order
;
38 import org
.hibernate
.criterion
.ProjectionList
;
39 import org
.hibernate
.criterion
.Projections
;
40 import org
.hibernate
.criterion
.Restrictions
;
41 import org
.hibernate
.criterion
.Subqueries
;
42 import org
.hibernate
.envers
.AuditReader
;
43 import org
.hibernate
.envers
.AuditReaderFactory
;
44 import org
.hibernate
.envers
.query
.AuditQuery
;
45 import org
.hibernate
.metadata
.ClassMetadata
;
46 import org
.hibernate
.sql
.JoinType
;
47 import org
.hibernate
.type
.Type
;
48 import org
.joda
.time
.DateTime
;
49 import org
.springframework
.beans
.factory
.annotation
.Autowired
;
50 import org
.springframework
.dao
.DataAccessException
;
51 import org
.springframework
.dao
.InvalidDataAccessApiUsageException
;
52 import org
.springframework
.security
.core
.Authentication
;
53 import org
.springframework
.security
.core
.context
.SecurityContextHolder
;
54 import org
.springframework
.util
.ReflectionUtils
;
56 import eu
.etaxonomy
.cdm
.model
.common
.CdmBase
;
57 import eu
.etaxonomy
.cdm
.model
.common
.IPublishable
;
58 import eu
.etaxonomy
.cdm
.model
.common
.VersionableEntity
;
59 import eu
.etaxonomy
.cdm
.model
.permission
.User
;
60 import eu
.etaxonomy
.cdm
.model
.view
.AuditEvent
;
61 import eu
.etaxonomy
.cdm
.persistence
.dao
.common
.ICdmEntityDao
;
62 import eu
.etaxonomy
.cdm
.persistence
.dao
.common
.Restriction
;
63 import eu
.etaxonomy
.cdm
.persistence
.dao
.common
.Restriction
.Operator
;
64 import eu
.etaxonomy
.cdm
.persistence
.dao
.initializer
.IBeanInitializer
;
65 import eu
.etaxonomy
.cdm
.persistence
.dto
.MergeResult
;
66 import eu
.etaxonomy
.cdm
.persistence
.hibernate
.PostMergeEntityListener
;
67 import eu
.etaxonomy
.cdm
.persistence
.hibernate
.replace
.ReferringObjectMetadata
;
68 import eu
.etaxonomy
.cdm
.persistence
.hibernate
.replace
.ReferringObjectMetadataFactory
;
69 import eu
.etaxonomy
.cdm
.persistence
.query
.Grouping
;
70 import eu
.etaxonomy
.cdm
.persistence
.query
.MatchMode
;
71 import eu
.etaxonomy
.cdm
.persistence
.query
.OrderHint
;
74 * Hibernate implementation for {@link ICdmEntityDao}.
76 public abstract class CdmEntityDaoBase
<T
extends CdmBase
>
78 implements ICdmEntityDao
<T
> {
80 private static final Logger logger
= LogManager
.getLogger(CdmEntityDaoBase
.class);
82 protected int flushAfterNo
= 1000; // large numbers may cause synchronisation errors
83 // when commiting the session
84 protected Class
<T
> type
;
87 // @Qualifier("defaultBeanInitializer")
88 protected IBeanInitializer defaultBeanInitializer
;
90 public void setDefaultBeanInitializer(IBeanInitializer defaultBeanInitializer
) {
91 this.defaultBeanInitializer
= defaultBeanInitializer
;
95 private ReferringObjectMetadataFactory referringObjectMetadataFactory
;
97 protected static final EnumSet
<Operator
> LEFTOUTER_OPS
= EnumSet
.of(Operator
.AND_NOT
, Operator
.OR
, Operator
.OR_NOT
);
99 public CdmEntityDaoBase(Class
<T
> type
) {
102 logger
.debug("Creating DAO of type [" + type
.getSimpleName() + "]");
106 public void lock(T t
, LockOptions lockOptions
) {
107 getSession().buildLockRequest(lockOptions
).lock(t
);
111 public void refresh(T t
, LockOptions lockOptions
, List
<String
> propertyPaths
) {
112 getSession().refresh(t
, lockOptions
);
113 defaultBeanInitializer
.initialize(t
, propertyPaths
);
116 // TODO this method should be moved to a concrete class (not typed)
117 public UUID
saveCdmObj(CdmBase cdmObj
) throws DataAccessException
{
118 getSession().saveOrUpdate(cdmObj
);
119 return cdmObj
.getUuid();
122 // TODO: Replace saveCdmObj() by saveCdmObject_
123 private UUID
saveCdmObject_(T cdmObj
) {
124 getSession().saveOrUpdate(cdmObj
);
125 return cdmObj
.getUuid();
128 // TODO: Use everywhere CdmEntityDaoBase.saveAll() instead of
129 // ServiceBase.saveCdmObjectAll()?
130 // TODO: why does this use saveCdmObject_ which actually savesOrUpdateds
133 public Map
<UUID
, T
> saveAll(Collection
<?
extends T
> cdmObjCollection
) {
134 int types
= cdmObjCollection
.getClass().getTypeParameters().length
;
136 if (logger
.isDebugEnabled()) {
137 logger
.debug("ClassType: + " + cdmObjCollection
.getClass().getTypeParameters()[0]);
141 Map
<UUID
, T
> resultMap
= new HashMap
<>();
142 Iterator
<?
extends T
> iterator
= cdmObjCollection
.iterator();
144 while (iterator
.hasNext()) {
145 if (((i
% 2000) == 0) && (i
> 0)) {
146 logger
.debug("Saved " + i
+ " objects");
148 T cdmObj
= iterator
.next();
149 UUID uuid
= saveCdmObject_(cdmObj
);
150 if (logger
.isDebugEnabled()) {
151 logger
.debug("Save cdmObj: " + (cdmObj
== null ?
null : cdmObj
.toString()));
153 resultMap
.put(uuid
, cdmObj
);
155 if ((i
% flushAfterNo
) == 0) {
157 if (logger
.isDebugEnabled()) {
158 logger
.debug("flush");
161 } catch (Exception e
) {
162 logger
.error("An exception occurred when trying to flush data");
164 throw new RuntimeException(e
);
169 if (logger
.isInfoEnabled()) {
170 logger
.info("Saved " + i
+ " objects");
175 private UUID
saveOrUpdateCdmObject(T cdmObj
) {
176 getSession().saveOrUpdate(cdmObj
);
177 return cdmObj
.getUuid();
181 public Map
<UUID
, T
> saveOrUpdateAll(Collection
<T
> cdmObjCollection
) {
182 int types
= cdmObjCollection
.getClass().getTypeParameters().length
;
184 if (logger
.isDebugEnabled()) {
185 logger
.debug("ClassType: + " + cdmObjCollection
.getClass().getTypeParameters()[0]);
189 Map
<UUID
, T
> resultMap
= new HashMap
<>();
190 Iterator
<T
> iterator
= cdmObjCollection
.iterator();
192 while (iterator
.hasNext()) {
193 if (((i
% 2000) == 0) && (i
> 0)) {
194 logger
.debug("Saved " + i
+ " objects");
196 T cdmObj
= iterator
.next();
197 UUID uuid
= saveOrUpdateCdmObject(cdmObj
);
198 if (logger
.isDebugEnabled()) {
199 logger
.debug("Save cdmObj: " + (cdmObj
== null ?
null : cdmObj
.toString()));
201 resultMap
.put(uuid
, cdmObj
);
203 if ((i
% flushAfterNo
) == 0) {
205 if (logger
.isDebugEnabled()) {
206 logger
.debug("flush");
209 } catch (Exception e
) {
210 logger
.error("An exception occurred when trying to flush data");
212 throw new RuntimeException(e
);
217 if (logger
.isInfoEnabled()) {
218 logger
.info("Saved " + i
+ " objects");
224 public T
replace(T x
, T y
) {
229 Class
<?
> commonClass
= x
.getClass();
231 while (!commonClass
.isAssignableFrom(y
.getClass())) {
232 if (commonClass
.equals(type
)) {
233 throw new RuntimeException();
235 commonClass
= commonClass
.getSuperclass();
239 getSession().merge(x
);
241 Set
<ReferringObjectMetadata
> referringObjectMetas
= referringObjectMetadataFactory
.get(x
.getClass());
243 for (ReferringObjectMetadata referringObjectMetadata
: referringObjectMetas
) {
245 List
<CdmBase
> referringObjects
= referringObjectMetadata
.getReferringObjects(x
, getSession());
247 for (CdmBase referringObject
: referringObjects
) {
249 referringObjectMetadata
.replace(referringObject
, x
, y
);
250 getSession().update(referringObject
);
252 } catch (IllegalArgumentException e
) {
253 throw new RuntimeException(e
.getMessage(), e
);
254 } catch (IllegalAccessException e
) {
255 throw new RuntimeException(e
.getMessage(), e
);
263 public Session
getSession() throws DataAccessException
{
264 return super.getSession();
268 public void clear() throws DataAccessException
{
269 Session session
= getSession();
271 if (logger
.isDebugEnabled()) {
272 logger
.debug("dao clear end");
277 public MergeResult
<T
> merge(T transientObject
, boolean returnTransientEntity
) throws DataAccessException
{
278 Session session
= getSession();
279 PostMergeEntityListener
.addSession(session
);
280 MergeResult
<T
> result
= null;
282 @SuppressWarnings("unchecked")
283 T persistentObject
= (T
) session
.merge(transientObject
);
284 if (logger
.isDebugEnabled()) {
285 logger
.debug("dao merge end");
288 if (returnTransientEntity
) {
289 if (transientObject
!= null && persistentObject
!= null) {
290 transientObject
.setId(persistentObject
.getId());
292 result
= new MergeResult(transientObject
, PostMergeEntityListener
.getNewEntities(session
));
294 result
= new MergeResult(persistentObject
, null);
298 PostMergeEntityListener
.removeSession(session
);
303 public T
merge(T transientObject
) throws DataAccessException
{
304 Session session
= getSession();
305 @SuppressWarnings("unchecked")
306 T persistentObject
= (T
) session
.merge(transientObject
);
307 if (logger
.isDebugEnabled()) {
308 logger
.debug("dao merge end");
310 return persistentObject
;
314 public UUID
saveOrUpdate(T transientObject
) throws DataAccessException
{
315 if (transientObject
== null) {
316 logger
.warn("Object to save should not be null. NOP");
320 if (logger
.isDebugEnabled()) {
321 logger
.debug("dao saveOrUpdate start...");
323 if (logger
.isDebugEnabled()) {
324 logger
.debug("transientObject(" + transientObject
.getClass().getSimpleName() + ") ID:"
325 + transientObject
.getId() + ", UUID: " + transientObject
.getUuid());
327 Session session
= getSession();
328 if (transientObject
.getId() != 0 && VersionableEntity
.class.isAssignableFrom(transientObject
.getClass())) {
329 VersionableEntity versionableEntity
= (VersionableEntity
) transientObject
;
330 versionableEntity
.setUpdated(new DateTime());
331 Authentication authentication
= SecurityContextHolder
.getContext().getAuthentication();
332 if (authentication
!= null && authentication
.getPrincipal() != null
333 && authentication
.getPrincipal() instanceof User
) {
334 User user
= (User
) authentication
.getPrincipal();
335 versionableEntity
.setUpdatedBy(user
);
338 session
.saveOrUpdate(transientObject
);
339 if (logger
.isDebugEnabled()) {
340 logger
.debug("dao saveOrUpdate end");
342 return transientObject
.getUuid();
343 } catch (NonUniqueObjectException e
) {
344 logger
.error("Error in CdmEntityDaoBase.saveOrUpdate(obj). ID=" + e
.getIdentifier() + ". Class="
345 + e
.getEntityName());
346 logger
.error(e
.getMessage());
350 } catch (HibernateException e
) {
358 public <S
extends T
> S
save(S newInstance
) throws DataAccessException
{
359 if (newInstance
== null) {
360 logger
.warn("Object to save should not be null. NOP");
363 getSession().save(newInstance
);
368 public UUID
update(T transientObject
) throws DataAccessException
{
369 if (transientObject
== null) {
370 logger
.warn("Object to update should not be null. NOP");
373 getSession().update(transientObject
);
374 return transientObject
.getUuid();
378 public UUID
refresh(T persistentObject
) throws DataAccessException
{
379 getSession().refresh(persistentObject
);
380 return persistentObject
.getUuid();
384 public UUID
delete(T persistentObject
) throws DataAccessException
{
385 if (persistentObject
== null) {
386 logger
.warn(type
.getName() + " was 'null'");
390 // Merge the object in if it is detached
392 // I think this is preferable to catching lazy initialization errors
393 // as that solution only swallows and hides the exception, but doesn't
394 // actually solve it.
395 persistentObject
= (T
) getSession().merge(persistentObject
);
396 getSession().delete(persistentObject
);
397 return persistentObject
.getUuid();
401 public T
findById(int id
) throws DataAccessException
{
402 return getSession().get(type
, id
);
406 public T
findByUuid(UUID uuid
) throws DataAccessException
{
407 return this.findByUuid(uuid
, INCLUDE_UNPUBLISHED
);
410 protected T
findByUuid(UUID uuid
, boolean includeUnpublished
) throws DataAccessException
{
411 Session session
= getSession();
412 Criteria crit
= session
.createCriteria(type
);
413 crit
.add(Restrictions
.eq("uuid", uuid
));
414 crit
.addOrder(Order
.desc("created"));
415 if (IPublishable
.class.isAssignableFrom(type
) && !includeUnpublished
) {
416 crit
.add(Restrictions
.eq("publish", Boolean
.TRUE
));
419 @SuppressWarnings("unchecked")
420 List
<T
> results
= crit
.list();
421 Set
<T
> resultSet
= new HashSet
<>();
422 resultSet
.addAll(results
);
423 if (resultSet
.isEmpty()) {
426 if (resultSet
.size() > 1) {
427 logger
.error("findByUuid() delivers more than one result for UUID: " + uuid
);
429 return results
.get(0);
434 public T
findByUuidWithoutFlush(UUID uuid
) throws DataAccessException
{
435 Session session
= getSession();
436 FlushMode currentFlushMode
= session
.getHibernateFlushMode();
438 // set flush mode to manual so that the session does not flush
439 // when before performing the query
440 session
.setHibernateFlushMode(FlushMode
.MANUAL
);
441 Criteria crit
= session
.createCriteria(type
);
442 crit
.add(Restrictions
.eq("uuid", uuid
));
443 crit
.addOrder(Order
.desc("created"));
444 @SuppressWarnings("unchecked")
445 List
<T
> results
= crit
.list();
446 if (results
.isEmpty()) {
449 if (results
.size() > 1) {
450 logger
.error("findByUuid() delivers more than one result for UUID: " + uuid
);
452 return results
.get(0);
455 // set back the session flush mode
456 if (currentFlushMode
!= null) {
457 session
.setHibernateFlushMode(currentFlushMode
);
463 public List
<T
> loadList(Collection
<Integer
> ids
, List
<OrderHint
> orderHints
, List
<String
> propertyPaths
) throws DataAccessException
{
466 return new ArrayList
<>(0);
469 Criteria criteria
= prepareList(null, ids
, null, null, orderHints
, "id");
471 if (logger
.isDebugEnabled()) {
472 logger
.debug(criteria
.toString());
475 @SuppressWarnings("unchecked")
476 List
<T
> result
= criteria
.list();
477 defaultBeanInitializer
.initializeAll(result
, propertyPaths
);
482 public List
<T
> list(Collection
<UUID
> uuids
, Integer pageSize
, Integer pageNumber
, List
<OrderHint
> orderHints
,
483 List
<String
> propertyPaths
) throws DataAccessException
{
485 if (uuids
== null || uuids
.isEmpty()) {
486 return new ArrayList
<>();
489 Criteria criteria
= prepareList(null, uuids
, pageSize
, pageNumber
, orderHints
, "uuid");
490 @SuppressWarnings("unchecked")
491 List
<T
> result
= criteria
.list();
492 defaultBeanInitializer
.initializeAll(result
, propertyPaths
);
497 public <S
extends T
> List
<S
> list(Class
<S
> clazz
, Collection
<UUID
> uuids
, Integer pageSize
, Integer pageNumber
, List
<OrderHint
> orderHints
,
498 List
<String
> propertyPaths
) throws DataAccessException
{
500 if (uuids
== null || uuids
.isEmpty()) {
501 return new ArrayList
<>();
504 Criteria criteria
= prepareList(clazz
, uuids
, pageSize
, pageNumber
, orderHints
, "uuid");
505 @SuppressWarnings("unchecked")
506 List
<S
> result
= criteria
.list();
507 defaultBeanInitializer
.initializeAll(result
, propertyPaths
);
512 public <S
extends T
> List
<S
> list(Class
<S
> type
, List
<Restriction
<?
>> restrictions
, Integer limit
, Integer start
,
513 List
<OrderHint
> orderHints
, List
<String
> propertyPaths
) {
515 Criteria criteria
= createCriteria(type
, restrictions
, false);
517 addLimitAndStart(criteria
, limit
, start
);
518 addOrder(criteria
, orderHints
);
520 @SuppressWarnings("unchecked")
521 List
<S
> result
= criteria
.list();
522 defaultBeanInitializer
.initializeAll(result
, propertyPaths
);
527 * @param restrictions
530 private void addRestrictions(List
<Restriction
<?
>> restrictions
, DetachedCriteria criteria
) {
532 if(restrictions
== null || restrictions
.isEmpty()){
536 List
<CriterionWithOperator
> perProperty
= new ArrayList
<>(restrictions
.size());
537 Map
<String
, String
> aliases
= new HashMap
<>();
541 for(Restriction
<?
> restriction
: restrictions
){
542 Collection
<?
extends Object
> values
= restriction
.getValues();
543 JoinType jointype
= LEFTOUTER_OPS
.contains(restriction
.getOperator()) ? JoinType
.LEFT_OUTER_JOIN
: JoinType
.INNER_JOIN
;
544 if(values
!= null && !values
.isEmpty()){
546 String propertyPath
= restriction
.getPropertyName();
547 String
[] props
= propertyPath
.split("\\.");
549 if(props
.length
== 1){
550 // direct property of the base type of the criteria
551 propertyName
= propertyPath
;
553 // create aliases if the propertyName is a dot separated property path
554 String aĺiasKey
= jointype
.name() + "_";
555 String aliasedProperty
= null;
557 for(int p
= 0; p
< props
.length
-1; p
++){
558 aĺiasKey
= aĺiasKey
+ (aĺiasKey
.isEmpty() ?
"" : ".") + props
[p
];
559 aliasedProperty
= alias
+ (alias
.isEmpty() ?
"" : ".") + props
[p
];
560 if(!aliases
.containsKey(aliasedProperty
)){
561 alias
= alias
+ (alias
.isEmpty() ?
"" : "_" ) + props
[p
];
562 aliases
.put(aĺiasKey
, alias
);
563 criteria
.createAlias(aliasedProperty
, alias
, jointype
);
564 if(logger
.isDebugEnabled()){
565 logger
.debug("addRestrictions() alias created with aliasKey " + aĺiasKey
+ " => " + aliasedProperty
+ " as " + alias
);
569 propertyName
= alias
+ "." + props
[props
.length
-1];
572 Criterion
[] predicates
= new Criterion
[values
.size()];
574 for(Object v
: values
){
575 Criterion criterion
= createRestriction(propertyName
, v
, restriction
.getMatchMode());
576 if(restriction
.isNot()){
577 if(props
.length
> 1){
578 criterion
= Restrictions
.or(Restrictions
.not(criterion
), Restrictions
.isNull(propertyName
));
580 criterion
= Restrictions
.not(criterion
);
583 predicates
[i
++] = criterion
;
584 if(logger
.isDebugEnabled()){
585 logger
.debug("addRestrictions() predicate with " + propertyName
+ " " + (restriction
.getMatchMode() == null ?
"=" : restriction
.getMatchMode().name()) + " " + v
.toString());
588 if(restriction
.getOperator() == Operator
.AND_NOT
){
589 perProperty
.add(new CriterionWithOperator(restriction
.getOperator(), Restrictions
.and(predicates
)));
591 perProperty
.add(new CriterionWithOperator(restriction
.getOperator(), Restrictions
.or(predicates
)));
593 } // check has values
594 } // loop over restrictions
596 Restriction
.Operator firstOperator
= null;
597 if(!perProperty
.isEmpty()){
598 LogicalExpression logicalExpression
= null;
599 for(CriterionWithOperator cwo
: perProperty
){
600 if(logicalExpression
== null){
601 firstOperator
= cwo
.operator
;
602 logicalExpression
= Restrictions
.and(Restrictions
.sqlRestriction("1=1"), cwo
.criterion
);
604 switch(cwo
.operator
){
607 logicalExpression
= Restrictions
.and(logicalExpression
, cwo
.criterion
);
611 logicalExpression
= Restrictions
.or(logicalExpression
, cwo
.criterion
);
614 throw new RuntimeException("Unsupported Operator");
621 criteria
.add(logicalExpression
);
622 // if(firstOperator == Operator.OR){
626 // criteria.add(Restrictions.and(queryStringCriterion, logicalExpression));
629 if(logger
.isDebugEnabled()){
630 logger
.debug("addRestrictions() final criteria: " + criteria
.toString());
635 * @param propertyName
638 * is only applied if the <code>value</code> is a
639 * <code>String</code> object
643 private Criterion
createRestriction(String propertyName
, Object value
, MatchMode matchMode
) {
645 Criterion restriction
;
647 if (logger
.isDebugEnabled()) {
648 logger
.debug("createRestriction() " + propertyName
+ " is null ");
650 restriction
= Restrictions
.isNull(propertyName
);
651 } else if (matchMode
== null || !(value
instanceof String
)) {
652 if (logger
.isDebugEnabled()) {
653 logger
.debug("createRestriction() " + propertyName
+ " = " + value
.toString());
655 restriction
= Restrictions
.eq(propertyName
, value
);
657 String queryString
= (String
) value
;
658 if (logger
.isDebugEnabled()) {
659 logger
.debug("createRestriction() " + propertyName
+ " " + matchMode
.getMatchOperator() + " "
660 + matchMode
.queryStringFrom(queryString
));
664 restriction
= Restrictions
.ilike(propertyName
, queryString
, org
.hibernate
.criterion
.MatchMode
.START
);
667 restriction
= Restrictions
.ilike(propertyName
, queryString
, org
.hibernate
.criterion
.MatchMode
.END
);
670 restriction
= Restrictions
.ilike(propertyName
, matchMode
.queryStringFrom(queryString
), org
.hibernate
.criterion
.MatchMode
.ANYWHERE
);
673 restriction
= Restrictions
.ilike(propertyName
, queryString
, org
.hibernate
.criterion
.MatchMode
.EXACT
);
676 restriction
= Restrictions
.ilike(propertyName
, queryString
, org
.hibernate
.criterion
.MatchMode
.ANYWHERE
);
679 throw new RuntimeException("Unknown MatchMode: " + matchMode
.name());
689 public long count(Class
<?
extends T
> type
, List
<Restriction
<?
>> restrictions
) {
691 Criteria criteria
= createCriteria(type
, restrictions
, false);
693 criteria
.setProjection(Projections
.projectionList().add(Projections
.rowCount()));
695 return (Long
) criteria
.uniqueResult();
704 * @param propertyName
707 private Criteria
prepareList(Class
<?
extends T
> clazz
, Collection
<?
> uuids
, Integer pageSize
, Integer pageNumber
, List
<OrderHint
> orderHints
,
708 String propertyName
) {
712 Criteria criteria
= getSession().createCriteria(clazz
);
713 criteria
.add(Restrictions
.in(propertyName
, uuids
));
715 if (pageSize
!= null) {
716 criteria
.setMaxResults(pageSize
);
717 if (pageNumber
!= null) {
718 criteria
.setFirstResult(pageNumber
* pageSize
);
720 criteria
.setFirstResult(0);
724 if (orderHints
== null) {
725 orderHints
= OrderHint
.defaultOrderHintsFor(type
);
727 addOrder(criteria
, orderHints
);
731 private Criteria
criterionForType(Class
<?
extends T
> clazz
) {
732 return getSession().createCriteria(entityType(clazz
));
735 protected Class
<?
extends T
> entityType(Class
<?
extends T
> clazz
){
744 public T
load(UUID uuid
) {
745 T bean
= findByUuid(uuid
);
749 defaultBeanInitializer
.load(bean
);
755 public T
load(int id
, List
<String
> propertyPaths
) {
756 T bean
= findById(id
);
760 defaultBeanInitializer
.initialize(bean
, propertyPaths
);
766 public T
loadWithoutInitializing(int id
){
767 return this.getSession().load(type
, id
);
771 public T
load(UUID uuid
, List
<String
> propertyPaths
) {
772 return this.load(uuid
, INCLUDE_UNPUBLISHED
, propertyPaths
);
775 protected T
load(UUID uuid
, boolean includeUnpublished
, List
<String
> propertyPaths
) {
776 T bean
= findByUuid(uuid
, includeUnpublished
);
780 defaultBeanInitializer
.initialize(bean
, propertyPaths
);
786 public Boolean
exists(UUID uuid
) {
787 if (findByUuid(uuid
) == null) {
794 public long count() {
799 public long count(Class
<?
extends T
> clazz
) {
800 Session session
= getSession();
801 Criteria criteria
= null;
803 criteria
= session
.createCriteria(type
);
805 criteria
= session
.createCriteria(clazz
);
807 criteria
.setProjection(Projections
.projectionList().add(Projections
.rowCount()));
809 // since hibernate 4 (or so) uniqueResult returns Long, not Integer,
811 // to be casted. Think about returning long rather then int!
812 return (long) criteria
.uniqueResult();
816 public List
<T
> list(Integer limit
, Integer start
) {
817 return list(limit
, start
, null);
821 public List
<Object
[]> group(Class
<?
extends T
> clazz
, Integer limit
, Integer start
, List
<Grouping
> groups
,
822 List
<String
> propertyPaths
) {
824 Criteria criteria
= null;
825 criteria
= criterionForType(clazz
);
827 addGroups(criteria
, groups
);
830 criteria
.setFirstResult(start
);
831 criteria
.setMaxResults(limit
);
834 @SuppressWarnings("unchecked")
835 List
<Object
[]> result
= criteria
.list();
837 if (propertyPaths
!= null && !propertyPaths
.isEmpty()) {
838 for (Object
[] objects
: result
) {
839 defaultBeanInitializer
.initialize(objects
[0], propertyPaths
);
846 protected void countGroups(DetachedCriteria criteria
, List
<Grouping
> groups
) {
847 if (groups
!= null) {
849 Map
<String
, String
> aliases
= new HashMap
<String
, String
>();
851 for (Grouping grouping
: groups
) {
852 if (grouping
.getAssociatedObj() != null) {
854 if ((alias
= aliases
.get(grouping
.getAssociatedObj())) == null) {
855 alias
= grouping
.getAssociatedObjectAlias();
856 aliases
.put(grouping
.getAssociatedObj(), alias
);
857 criteria
.createAlias(grouping
.getAssociatedObj(), alias
);
862 ProjectionList projectionList
= Projections
.projectionList();
864 for (Grouping grouping
: groups
) {
865 grouping
.addProjection(projectionList
);
867 criteria
.setProjection(projectionList
);
871 protected void addGroups(Criteria criteria
, List
<Grouping
> groups
) {
872 if (groups
!= null) {
874 Map
<String
, String
> aliases
= new HashMap
<String
, String
>();
876 for (Grouping grouping
: groups
) {
877 if (grouping
.getAssociatedObj() != null) {
879 if ((alias
= aliases
.get(grouping
.getAssociatedObj())) == null) {
880 alias
= grouping
.getAssociatedObjectAlias();
881 aliases
.put(grouping
.getAssociatedObj(), alias
);
882 criteria
.createAlias(grouping
.getAssociatedObj(), alias
);
887 ProjectionList projectionList
= Projections
.projectionList();
889 for (Grouping grouping
: groups
) {
890 grouping
.addProjection(projectionList
);
892 criteria
.setProjection(projectionList
);
894 for (Grouping grouping
: groups
) {
895 grouping
.addOrder(criteria
);
902 public List
<T
> list(Integer limit
, Integer start
, List
<OrderHint
> orderHints
) {
903 return list(limit
, start
, orderHints
, null);
907 public List
<T
> list(Integer limit
, Integer start
, List
<OrderHint
> orderHints
, List
<String
> propertyPaths
) {
908 Criteria criteria
= getSession().createCriteria(type
);
910 criteria
.setFirstResult(start
);
911 criteria
.setMaxResults(limit
);
914 addOrder(criteria
, orderHints
);
915 @SuppressWarnings("unchecked")
916 List
<T
> results
= criteria
.list();
918 defaultBeanInitializer
.initializeAll(results
, propertyPaths
);
923 public <S
extends T
> List
<S
> list(Class
<S
> clazz
, Integer limit
, Integer start
, List
<OrderHint
> orderHints
,
924 List
<String
> propertyPaths
) {
925 Criteria criteria
= null;
927 criteria
= getSession().createCriteria(type
);
929 criteria
= getSession().createCriteria(clazz
);
932 addLimitAndStart(criteria
, limit
, start
);
934 addOrder(criteria
, orderHints
);
936 @SuppressWarnings("unchecked")
937 List
<S
> results
= criteria
.list();
939 defaultBeanInitializer
.initializeAll(results
, propertyPaths
);
943 public <S
extends T
> List
<S
> list(Class
<S
> type
, Integer limit
, Integer start
, List
<OrderHint
> orderHints
) {
944 return list(type
, limit
, start
, orderHints
, null);
948 public <S
extends T
> List
<S
> list(Class
<S
> type
, Integer limit
, Integer start
) {
949 return list(type
, limit
, start
, null, null);
953 public Class
<T
> getType() {
958 public long count(T example
, Set
<String
> includeProperties
) {
959 Criteria criteria
= getSession().createCriteria(example
.getClass());
960 addExample(criteria
, example
, includeProperties
);
962 criteria
.setProjection(Projections
.rowCount());
963 return (Long
) criteria
.uniqueResult();
966 protected void addExample(Criteria criteria
, T example
, Set
<String
> includeProperties
) {
967 if (includeProperties
!= null && !includeProperties
.isEmpty()) {
968 criteria
.add(Example
.create(example
).setPropertySelector(new PropertySelectorImpl(includeProperties
)));
969 ClassMetadata classMetadata
= getSession().getSessionFactory().getClassMetadata(example
.getClass());
970 for (String property
: includeProperties
) {
971 Type type
= classMetadata
.getPropertyType(property
);
972 if (type
.isEntityType()) {
974 Field field
= ReflectionUtils
.findField(example
.getClass(), property
);
975 field
.setAccessible(true);
976 Object value
= field
.get(example
);
978 criteria
.add(Restrictions
.eq(property
, value
));
980 criteria
.add(Restrictions
.isNull(property
));
982 } catch (SecurityException se
) {
983 throw new InvalidDataAccessApiUsageException("Tried to add criteria for property " + property
,
985 } catch (HibernateException he
) {
986 throw new InvalidDataAccessApiUsageException("Tried to add criteria for property " + property
,
988 } catch (IllegalArgumentException iae
) {
989 throw new InvalidDataAccessApiUsageException("Tried to add criteria for property " + property
,
991 } catch (IllegalAccessException ie
) {
992 throw new InvalidDataAccessApiUsageException("Tried to add criteria for property " + property
,
998 criteria
.add(Example
.create(example
));
1004 * NOTE: We can't reuse
1005 * {@link #list(Class, String, Object, MatchMode, Integer, Integer, List, List)
1006 * here due to different default behavior of the <code>matchmode</code>
1011 * @param queryString
1017 * @param propertyPaths
1021 public <S
extends T
> List
<S
> findByParam(Class
<S
> clazz
, String param
, String queryString
, MatchMode matchmode
,
1022 List
<Criterion
> criterion
, Integer pageSize
, Integer pageNumber
, List
<OrderHint
> orderHints
,
1023 List
<String
> propertyPaths
) {
1024 Set
<String
> stringSet
= new HashSet
<>();
1025 stringSet
.add(param
);
1026 return this.findByParam(clazz
, stringSet
, queryString
, matchmode
,
1027 criterion
, pageSize
, pageNumber
, orderHints
,
1032 public <S
extends T
> List
<S
> findByParam(Class
<S
> clazz
, Set
<String
> params
, String queryString
, MatchMode matchmode
,
1033 List
<Criterion
> criterion
, Integer pageSize
, Integer pageNumber
, List
<OrderHint
> orderHints
,
1034 List
<String
> propertyPaths
) {
1036 Criteria criteria
= criterionForType(clazz
);
1038 if (queryString
!= null) {
1039 Set
<Criterion
> criterions
= new HashSet
<>();
1040 for (String param
: params
){
1042 if (matchmode
== null) {
1043 crit
= Restrictions
.ilike(param
, queryString
);
1044 } else if (matchmode
== MatchMode
.BEGINNING
) {
1045 crit
= Restrictions
.ilike(param
, queryString
, org
.hibernate
.criterion
.MatchMode
.START
);
1046 } else if (matchmode
== MatchMode
.END
) {
1047 crit
= Restrictions
.ilike(param
, queryString
, org
.hibernate
.criterion
.MatchMode
.END
);
1048 } else if (matchmode
== MatchMode
.EXACT
) {
1049 crit
= Restrictions
.ilike(param
, queryString
, org
.hibernate
.criterion
.MatchMode
.EXACT
);
1051 crit
= Restrictions
.ilike(param
, queryString
, org
.hibernate
.criterion
.MatchMode
.ANYWHERE
);
1053 criterions
.add(crit
);
1055 if (criterions
.size()>1){
1056 Iterator
<Criterion
> critIterator
= criterions
.iterator();
1057 Disjunction disjunction
= Restrictions
.disjunction();
1058 while (critIterator
.hasNext()){
1059 disjunction
.add(critIterator
.next());
1061 criteria
.add(disjunction
);
1063 if (!criterions
.isEmpty()){
1064 criteria
.add(criterions
.iterator().next());
1069 addCriteria(criteria
, criterion
);
1071 addPageSizeAndNumber(criteria
, pageSize
, pageNumber
);
1072 addOrder(criteria
, orderHints
);
1074 @SuppressWarnings("unchecked")
1075 List
<S
> result
= criteria
.list();
1076 defaultBeanInitializer
.initializeAll(result
, propertyPaths
);
1081 public long countByParam(Class
<?
extends T
> clazz
, String param
, String queryString
, MatchMode matchmode
,
1082 List
<Criterion
> criterion
) {
1084 Criteria criteria
= null;
1086 criteria
= criterionForType(clazz
);
1088 if (queryString
!= null) {
1089 if (matchmode
== null) {
1090 criteria
.add(Restrictions
.ilike(param
, queryString
));
1091 } else if (matchmode
== MatchMode
.BEGINNING
) {
1092 criteria
.add(Restrictions
.ilike(param
, queryString
, org
.hibernate
.criterion
.MatchMode
.START
));
1093 } else if (matchmode
== MatchMode
.END
) {
1094 criteria
.add(Restrictions
.ilike(param
, queryString
, org
.hibernate
.criterion
.MatchMode
.END
));
1095 } else if (matchmode
== MatchMode
.EXACT
) {
1096 criteria
.add(Restrictions
.ilike(param
, queryString
, org
.hibernate
.criterion
.MatchMode
.EXACT
));
1098 criteria
.add(Restrictions
.ilike(param
, queryString
, org
.hibernate
.criterion
.MatchMode
.ANYWHERE
));
1102 addCriteria(criteria
, criterion
);
1104 criteria
.setProjection(Projections
.rowCount());
1106 return (Long
) criteria
.uniqueResult();
1110 * Creates a criteria query for the CDM <code>type</code> either for counting or listing matching entities.
1112 * The set of matching entities can be restricted by passing a list of {@link Restriction} objects.
1113 * Restrictions can logically combined:
1116 new Restriction<String>("titleCache", MatchMode.ANYWHERE, "foo"),
1117 new Restriction<String>("institute.name", Operator.OR, MatchMode.BEGINNING, "Bar")
1120 * The first Restriction in the example above by default has the <code>Operator.AND</code> which will be
1121 * ignored since this is the first restriction. The <code>Operator</code> of further restrictions in the
1122 * list are used to combine with the previous restriction.
1125 * @param restrictions
1129 protected Criteria
createCriteria(Class
<?
extends T
> type
, List
<Restriction
<?
>> restrictions
, boolean doCount
) {
1131 DetachedCriteria idsOnlyCriteria
= DetachedCriteria
.forClass(entityType(type
));
1132 idsOnlyCriteria
.setProjection(Projections
.distinct(Projections
.id()));
1134 addRestrictions(restrictions
, idsOnlyCriteria
);
1136 Criteria criteria
= criterionForType(type
);
1137 criteria
.add(Subqueries
.propertyIn("id", idsOnlyCriteria
));
1140 criteria
.setProjection(Projections
.rowCount());
1142 idsOnlyCriteria
.setProjection(Projections
.distinct(Projections
.property("id")));
1150 public <S
extends T
> List
<S
> findByParamWithRestrictions(Class
<S
> clazz
, String param
, String queryString
,
1151 MatchMode matchmode
, List
<Restriction
<?
>> restrictions
, Integer pageSize
, Integer pageNumber
,
1152 List
<OrderHint
> orderHints
, List
<String
> propertyPaths
) {
1154 List
<Restriction
<?
>> allRestrictions
= new ArrayList
<>();
1155 allRestrictions
.add(new Restriction
<String
>(param
, matchmode
, queryString
));
1156 if(restrictions
!= null){
1157 allRestrictions
.addAll(restrictions
);
1159 Criteria criteria
= createCriteria(clazz
, allRestrictions
, false);
1161 addPageSizeAndNumber(criteria
, pageSize
, pageNumber
);
1163 addOrder(criteria
, orderHints
);
1165 @SuppressWarnings("unchecked")
1166 List
<S
> result
= criteria
.list();
1167 defaultBeanInitializer
.initializeAll(result
, propertyPaths
);
1173 public long countByParamWithRestrictions(Class
<?
extends T
> clazz
, String param
, String queryString
,
1174 MatchMode matchmode
, List
<Restriction
<?
>> restrictions
) {
1176 List
<Restriction
<?
>> allRestrictions
= new ArrayList
<>();
1177 allRestrictions
.add(new Restriction
<String
>(param
, matchmode
, queryString
));
1178 if(restrictions
!= null){
1179 allRestrictions
.addAll(restrictions
);
1181 Criteria criteria
= createCriteria(clazz
, allRestrictions
, true);
1183 return (Long
) criteria
.uniqueResult();
1187 public <S
extends T
> List
<S
> list(S example
, Set
<String
> includeProperties
, Integer limit
, Integer start
,
1188 List
<OrderHint
> orderHints
, List
<String
> propertyPaths
) {
1189 Criteria criteria
= getSession().createCriteria(example
.getClass());
1190 addExample(criteria
, example
, includeProperties
);
1192 addLimitAndStart(criteria
, limit
, start
);
1194 addOrder(criteria
, orderHints
);
1196 @SuppressWarnings("unchecked")
1197 List
<S
> results
= criteria
.list();
1198 defaultBeanInitializer
.initializeAll(results
, propertyPaths
);
1202 private class PropertySelectorImpl
implements PropertySelector
{
1204 private final Set
<String
> includeProperties
;
1208 private static final long serialVersionUID
= -3175311800911570546L;
1210 public PropertySelectorImpl(Set
<String
> includeProperties
) {
1211 this.includeProperties
= includeProperties
;
1215 public boolean include(Object propertyValue
, String propertyName
, Type type
) {
1216 if (includeProperties
.contains(propertyName
)) {
1225 private class CriterionWithOperator
{
1227 Restriction
.Operator operator
;
1228 Criterion criterion
;
1231 public CriterionWithOperator(Operator operator
, Criterion criterion
) {
1233 this.operator
= operator
;
1234 this.criterion
= criterion
;
1241 * Returns a Criteria for the given {@link Class class} or, if
1242 * <code>null</code>, for the base {@link Class class} of this DAO.
1245 * @return the Criteria
1247 protected Criteria
getCriteria(Class
<?
extends CdmBase
> clazz
) {
1248 Criteria criteria
= null;
1249 if (clazz
== null) {
1250 criteria
= getSession().createCriteria(type
);
1252 criteria
= getSession().createCriteria(clazz
);
1262 protected AuditQuery
makeAuditQuery(Class
<?
extends CdmBase
> clazz
, AuditEvent auditEvent
) {
1263 AuditQuery query
= null;
1265 if (clazz
== null) {
1266 query
= getAuditReader().createQuery().forEntitiesAtRevision(type
, auditEvent
.getRevisionNumber());
1268 query
= getAuditReader().createQuery().forEntitiesAtRevision(clazz
, auditEvent
.getRevisionNumber());
1273 protected AuditReader
getAuditReader() {
1274 return AuditReaderFactory
.get(getSession());