ClobReaderTypeHandler.java

  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. import java.io.Reader;
  18. import java.sql.CallableStatement;
  19. import java.sql.Clob;
  20. import java.sql.PreparedStatement;
  21. import java.sql.ResultSet;
  22. import java.sql.SQLException;

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

  31.   /**
  32.    * Set a {@link Reader} into {@link PreparedStatement}.
  33.    *
  34.    * @see PreparedStatement#setClob(int, Reader)
  35.    */
  36.   @Override
  37.   public void setNonNullParameter(PreparedStatement ps, int i, Reader parameter, JdbcType jdbcType)
  38.       throws SQLException {
  39.     ps.setClob(i, parameter);
  40.   }

  41.   /**
  42.    * Get a {@link Reader} that corresponds to a specified column name from {@link ResultSet}.
  43.    *
  44.    * @see ResultSet#getClob(String)
  45.    */
  46.   @Override
  47.   public Reader getNullableResult(ResultSet rs, String columnName) throws SQLException {
  48.     return toReader(rs.getClob(columnName));
  49.   }

  50.   /**
  51.    * Get a {@link Reader} that corresponds to a specified column index from {@link ResultSet}.
  52.    *
  53.    * @see ResultSet#getClob(int)
  54.    */
  55.   @Override
  56.   public Reader getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
  57.     return toReader(rs.getClob(columnIndex));
  58.   }

  59.   /**
  60.    * Get a {@link Reader} that corresponds to a specified column index from {@link CallableStatement}.
  61.    *
  62.    * @see CallableStatement#getClob(int)
  63.    */
  64.   @Override
  65.   public Reader getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
  66.     return toReader(cs.getClob(columnIndex));
  67.   }

  68.   private Reader toReader(Clob clob) throws SQLException {
  69.     if (clob == null) {
  70.       return null;
  71.     }
  72.     return clob.getCharacterStream();
  73.   }

  74. }