BlobInputStreamTypeHandler.java

  1. /*
  2.  *    Copyright 2009-2021 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.apache.ibatis.type;

  17. import java.io.InputStream;
  18. import java.sql.Blob;
  19. import java.sql.CallableStatement;
  20. import java.sql.PreparedStatement;
  21. import java.sql.ResultSet;
  22. import java.sql.SQLException;

  23. /**
  24.  * The {@link TypeHandler} for {@link Blob}/{@link InputStream} using method supported at JDBC 4.0.
  25.  * @since 3.4.0
  26.  * @author Kazuki Shimizu
  27.  */
  28. public class BlobInputStreamTypeHandler extends BaseTypeHandler<InputStream> {

  29.   /**
  30.    * Set an {@link InputStream} into {@link PreparedStatement}.
  31.    * @see PreparedStatement#setBlob(int, InputStream)
  32.    */
  33.   @Override
  34.   public void setNonNullParameter(PreparedStatement ps, int i, InputStream parameter, JdbcType jdbcType)
  35.       throws SQLException {
  36.     ps.setBlob(i, parameter);
  37.   }

  38.   /**
  39.    * Get an {@link InputStream} that corresponds to a specified column name from {@link ResultSet}.
  40.    * @see ResultSet#getBlob(String)
  41.    */
  42.   @Override
  43.   public InputStream getNullableResult(ResultSet rs, String columnName)
  44.       throws SQLException {
  45.     return toInputStream(rs.getBlob(columnName));
  46.   }

  47.   /**
  48.    * Get an {@link InputStream} that corresponds to a specified column index from {@link ResultSet}.
  49.    * @see ResultSet#getBlob(int)
  50.    */
  51.   @Override
  52.   public InputStream getNullableResult(ResultSet rs, int columnIndex)
  53.       throws SQLException {
  54.     return toInputStream(rs.getBlob(columnIndex));
  55.   }

  56.   /**
  57.    * Get an {@link InputStream} that corresponds to a specified column index from {@link CallableStatement}.
  58.    * @see CallableStatement#getBlob(int)
  59.    */
  60.   @Override
  61.   public InputStream getNullableResult(CallableStatement cs, int columnIndex)
  62.       throws SQLException {
  63.     return toInputStream(cs.getBlob(columnIndex));
  64.   }

  65.   private InputStream toInputStream(Blob blob) throws SQLException {
  66.     if (blob == null) {
  67.       return null;
  68.     } else {
  69.       return blob.getBinaryStream();
  70.     }
  71.   }

  72. }