View Javadoc
1   /*
2    *    Copyright 2009-2023 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    *       https://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  
18  import java.io.InputStream;
19  import java.sql.Blob;
20  import java.sql.CallableStatement;
21  import java.sql.PreparedStatement;
22  import java.sql.ResultSet;
23  import java.sql.SQLException;
24  
25  /**
26   * The {@link TypeHandler} for {@link Blob}/{@link InputStream} using method supported at JDBC 4.0.
27   *
28   * @since 3.4.0
29   *
30   * @author Kazuki Shimizu
31   */
32  public class BlobInputStreamTypeHandler extends BaseTypeHandler<InputStream> {
33  
34    /**
35     * Set an {@link InputStream} into {@link PreparedStatement}.
36     *
37     * @see PreparedStatement#setBlob(int, InputStream)
38     */
39    @Override
40    public void setNonNullParameter(PreparedStatement ps, int i, InputStream parameter, JdbcType jdbcType)
41        throws SQLException {
42      ps.setBlob(i, parameter);
43    }
44  
45    /**
46     * Get an {@link InputStream} that corresponds to a specified column name from {@link ResultSet}.
47     *
48     * @see ResultSet#getBlob(String)
49     */
50    @Override
51    public InputStream getNullableResult(ResultSet rs, String columnName) throws SQLException {
52      return toInputStream(rs.getBlob(columnName));
53    }
54  
55    /**
56     * Get an {@link InputStream} that corresponds to a specified column index from {@link ResultSet}.
57     *
58     * @see ResultSet#getBlob(int)
59     */
60    @Override
61    public InputStream getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
62      return toInputStream(rs.getBlob(columnIndex));
63    }
64  
65    /**
66     * Get an {@link InputStream} that corresponds to a specified column index from {@link CallableStatement}.
67     *
68     * @see CallableStatement#getBlob(int)
69     */
70    @Override
71    public InputStream getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
72      return toInputStream(cs.getBlob(columnIndex));
73    }
74  
75    private InputStream toInputStream(Blob blob) throws SQLException {
76      if (blob == null) {
77        return null;
78      }
79      return blob.getBinaryStream();
80    }
81  
82  }