private void verifyReferencesExist ( String referringTableName , Multimap < Table , String > referencesPerTable ) throws SQLException { for ( Table referencedTable : referencesPerTable . keySet ( ) ) { LOG . info ( "Checking {} references to {}" , referringTableName , referencedTable . name ) ; Collection < String > referenceStrings = referencesPerTable . get ( referencedTable ) ; String referenceFieldName = referencedTable . getKeyFieldName ( ) ; String questionMarks = String . join ( ", " , Collections . nCopies ( referenceStrings . size ( ) , "?" ) ) ; String checkCountSql = String . format ( "select %s from %s.%s where %s in (%s)" , referenceFieldName , tablePrefix , referencedTable . name , referenceFieldName , questionMarks ) ; PreparedStatement preparedStatement = connection . prepareStatement ( checkCountSql ) ; int oneBasedIndex = 1 ; for ( String ref : referenceStrings ) { preparedStatement . setString ( oneBasedIndex ++ , ref ) ; } LOG . info ( preparedStatement . toString ( ) ) ; ResultSet resultSet = preparedStatement . executeQuery ( ) ; Set < String > foundReferences = new HashSet <> ( ) ; while ( resultSet . next ( ) ) { String referenceValue = resultSet . getString ( 1 ) ; foundReferences . add ( referenceValue ) ; } // Determine if any references were not found. referenceStrings . removeAll ( foundReferences ) ; if ( referenceStrings . size ( ) > 0 ) { throw new SQLException ( String . format ( "%s entities must contain valid %s references. (Invalid references: %s)" , referringTableName , referenceFieldName , String . join ( ", " , referenceStrings ) ) ) ; } else { LOG . info ( "All {} {} {} references are valid." , foundReferences . size ( ) , referencedTable . name , referenceFieldName ) ; } } }
Checks that a set of string references to a set of reference tables are all valid . For each set of references mapped to a reference table the method queries for all of the references . If there are any references that were not returned in the query one of the original references was invalid and an exception is thrown .