1. /*
  2. * Copyright 2002-2004 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.dao.support;
  17. import java.util.Collection;
  18. import org.springframework.dao.IncorrectResultSizeDataAccessException;
  19. /**
  20. * Miscellaneous utility methods for DAO implementations.
  21. * Useful with any data access technology.
  22. * @author Juergen Hoeller
  23. * @since 26.05.2004
  24. */
  25. public abstract class DataAccessUtils {
  26. /**
  27. * Return a unique result object from the given Collection.
  28. * Returns null if 0 result objects found; throws an exception
  29. * if more than 1 found.
  30. * @param results the result Collection
  31. * @return the unique result object, or null if none
  32. * @throws IncorrectResultSizeDataAccessException if more than one
  33. * result object has been found in the given Collection
  34. */
  35. public static Object uniqueResult(Collection results) throws IncorrectResultSizeDataAccessException {
  36. int size = results.size();
  37. if (size == 0) {
  38. return null;
  39. }
  40. if (size > 1) {
  41. throw new IncorrectResultSizeDataAccessException(1, size);
  42. }
  43. return results.iterator().next();
  44. }
  45. /**
  46. * Return a unique result object from the given Collection.
  47. * Throws an exception if 0 or more than 1 result objects found.
  48. * @param results the result Collection
  49. * @return the unique result object, or null if none
  50. * @throws IncorrectResultSizeDataAccessException if more than one
  51. * result object has been found in the given Collection
  52. */
  53. public static Object requiredUniqueResult(Collection results) throws IncorrectResultSizeDataAccessException {
  54. Object result = uniqueResult(results);
  55. if (result == null) {
  56. return new IncorrectResultSizeDataAccessException(1, 0);
  57. }
  58. return result;
  59. }
  60. }