public static String buildWhereClause ( Object object , MapSqlParameterSource params ) throws IllegalAccessException , InvocationTargetException , NoSuchMethodException { LOGGER . debug ( "Building query" ) ; final StringBuilder query = new StringBuilder ( ) ; boolean first = true ; for ( Field field : object . getClass ( ) . getDeclaredFields ( ) ) { if ( field . isAnnotationPresent ( QueryWhereClause . class ) || field . isAnnotationPresent ( QueryWhereClauses . class ) ) { final String fieldName = field . getName ( ) ; LOGGER . trace ( "New annotated field found: {}" , fieldName ) ; QueryWhereClause [ ] annotations = field . getAnnotationsByType ( QueryWhereClause . class ) ; for ( QueryWhereClause annotation : annotations ) { String whereValue = annotation . value ( ) ; int [ ] types = annotation . fieldTypes ( ) ; int index = 0 ; LOGGER . trace ( "Unprocessed whereClause: {}" , whereValue ) ; Matcher matcher = PARAM_PATTERN . matcher ( whereValue ) ; boolean hasValue = false ; while ( matcher . find ( ) ) { String originalParam = matcher . group ( 1 ) ; LOGGER . debug ( "New parameter found in the query: {}" , originalParam ) ; String convertedParam = originalParam . replaceAll ( "this" , fieldName ) ; Object value = null ; try { value = BeanUtils . getNestedProperty ( object , convertedParam ) ; } catch ( NestedNullException e ) { LOGGER . info ( "Bean not accessible= {}" , e . getMessage ( ) ) ; } if ( value == null ) { LOGGER . debug ( "Param {} was null, ignoring in the query" , convertedParam ) ; } else { hasValue = true ; whereValue = StringUtils . replace ( whereValue , "{" + originalParam + "}" , ":" + convertedParam ) ; if ( params != null ) { if ( index <= types . length - 1 ) { params . addValue ( convertedParam , value , types [ index ] ) ; } else { params . addValue ( convertedParam , value ) ; } } } index ++ ; } if ( hasValue ) { if ( ! first ) { query . append ( " AND " ) ; } else { first = false ; } query . append ( whereValue ) ; } } } } LOGGER . debug ( "built query={}" , query ) ; return query . toString ( ) ; }
Builds a where clause based upon the object values