Browse Source

ref:判断数据库返回字段类型是否为CLOB

liusw 5 years ago
parent
commit
a156be52a5
1 changed files with 46 additions and 5 deletions
  1. 46 5
      src/main/java/com/uas/erp/database/repository/BaseRepository.java

+ 46 - 5
src/main/java/com/uas/erp/database/repository/BaseRepository.java

@@ -1,5 +1,6 @@
 package com.uas.erp.database.repository;
 
+import oracle.sql.CLOB;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.dao.DataAccessException;
 import org.springframework.dao.EmptyResultDataAccessException;
@@ -9,10 +10,10 @@ import org.springframework.jdbc.core.JdbcTemplate;
 import org.springframework.jdbc.core.RowMapper;
 import org.springframework.stereotype.Repository;
 
-import java.sql.CallableStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Types;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.Reader;
+import java.sql.*;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -70,7 +71,12 @@ public class BaseRepository {
                     Map<String, Object> data = new HashMap<>();
                     for (String field : fields) {
                         try {
-                            data.put(field, rs.getObject(field));
+                            // 判断字段类型是否为CLOB
+                            if (rs.getObject(field) instanceof CLOB) {
+                                data.put(field, ClobToString(rs.getClob(field)));
+                            } else {
+                                data.put(field, rs.getObject(field));
+                            }
                         } catch (SQLException e) {
                             // ignore non-exists fields
                         }
@@ -83,6 +89,41 @@ public class BaseRepository {
         }
     }
 
+    /**
+     * clob字段转String
+     * @param clob
+     * @return
+     */
+    public String ClobToString(Clob clob) {
+        String reString = "";
+        Reader is = null;
+        try {
+            is = clob.getCharacterStream();
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+        // 得到流
+        BufferedReader br = new BufferedReader(is);
+        String s = null;
+        try {
+            s = br.readLine();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        StringBuffer sb = new StringBuffer();
+        while (s != null) {
+            //执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
+            sb.append(s);
+            try {
+                s = br.readLine();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        reString = sb.toString();
+        return reString;
+    }
+
     public <T> List<T> queryForList(String exec, Class<T> targetCls, Object... vars) {
         try {
             return jdbcTemplate.queryForList(exec, targetCls, vars);