zm
2020-05-18 a18bfacbf56b401f6e0fdae8710fbca4df8cff77
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package com.changhong.autoform.core.mapper;
 
import com.changhong.autoform.constant.system.ErrCode;
import com.changhong.autoform.core.exception.AutoFormException;
import com.changhong.autoform.core.filter.SelectSqlFilter;
import com.changhong.autoform.core.filter.UpdateSqlFilter;
import com.changhong.autoform.core.spring.SpringContext;
import com.changhong.autoform.core.tool.Keys;
import com.changhong.autoform.core.tool.ThreadTool;
import com.changhong.autoform.entity.ColunmsFieldEntity;
import com.changhong.autoform.entity.sql.Sql;
import com.changhong.autoform.entity.sql.delete.Delete;
import com.changhong.autoform.entity.sql.insert.Insert;
import com.changhong.autoform.entity.sql.select.Select;
import com.changhong.autoform.entity.sql.update.Update;
import org.springframework.beans.factory.annotation.Autowired;
 
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class BaseMapper implements ErrCode{
 
    private static final Logger log = Logger.getLogger(BaseMapper.class.getName());
    
    protected DataSource getDataSource() {
        return SpringContext.getBean(DataSource.class, (String beanName)->{
            return "dataSource".equalsIgnoreCase(beanName);
        });
    }
 
    @Autowired(required=false)
    private SelectSqlFilter selectFilter;
 
    @Autowired(required=false)
    private UpdateSqlFilter updateFilter;
 
    protected Connection getConnection() {
        DataSource ds = ThreadTool.get(Keys.DATA_SOURCE);
        try {
            if(ds == null){
                return (ds = getDataSource()).getConnection();
            }else{
                return ds.getConnection();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new AutoFormException(CONNECT_ERR);
        }finally {
            //            ThreadTool.set(Keys.DATA_SOURCE, ds);
        }
    }
 
    public int execute(Delete delete){
        return update(delete);
    }
 
    public int execute(Update update){
        return update(update);
    }
 
    public int execute(Insert insert){
        return update(insert);
    }
 
    public Map<String, Object> selectOne(Select select){
        return selectOne(select, (index, key, rs, result)->{
            result.put(key, rs.getString(index));
        });
    }
 
    public Map<String, Object> selectOne(Select select, SelectFilter selectFilter){
        final Map<String, Object> map = new HashMap<>();
        select(select, (fields, rs)->{
            if(rs.next()){
                for (int i = 0; i < fields.length; i++) {
                    selectFilter.filter(i+1, fields[i], rs, map);
                }
            }
        });
        return map;
    }
 
    public List<Map<String, Object>> selectList(Select select){
        return selectList(select, (index, key, rs, result)->{
            result.put(key, rs.getString(index));
        });
    }
 
    public List<Map<String, Object>> selectList(Select select, SelectFilter selectFilter){
        List<Map<String, Object>> list = new ArrayList<>();
        select(select, (fields, rs)->{
            while(rs.next()){
                Map<String, Object> map = new HashMap<>();
                for (int i = 0; i < fields.length; i++) {
                    selectFilter.filter(i+1, fields[i], rs, map);
                }
                list.add(map);
            }
        });
        return list;
    }
 
    /*    public List<String> selectFieldValue(Select select){
        return selectFieldValue(select, (index, rs, result, list)->{
            result.add(rs.getString(index));
        });
    }
 
    public List<String> selectFieldValue(Select select, SelectFieldFilter selectFieldFilter){
        String value = "";
        select(select, (fields, rs)->{
            while(rs.next()){
                for (int i = 0; i < fields.length; i++) {
                    selectFieldFilter.filter(i+1, fields[i], rs, value);
                }
                list.add(value);
            }
        });
        return list;
    }*/
 
 
    protected Integer getLastInsertId(Connection connection) {
        try(PreparedStatement ps = connection.prepareStatement("SELECT LAST_INSERT_ID()");    
                ResultSet rs = ps.executeQuery();
                ){
            if(rs.next()){
                return rs.getInt(1);
            }else{
                return 0;
            }
        }catch(SQLException e){
            e.printStackTrace();
            throw new AutoFormException(EXECUTE_ERR);
        }
    }
 
    protected void select(Select select, ResultSetFilter rsf){
        String[] fields = select.getFields();
        Connection connection = getConnection();
        ResultSet rs = null;
        PreparedStatement ps = null;
        String sql = null;
        Object[] args = null;
        try{
            long begen = System.currentTimeMillis();
            ps = connection.prepareStatement(
                    (sql = selectFilter == null ? select.getSql() : selectFilter.filter(select.getSql()))
                );
            args = select.getParams();
            log.log(Level.WARNING, String.format("参数:%s", Arrays.toString(args)));
            log.log(Level.WARNING, String.format("sql:%s", sql));
            if(args.length > 0){
                for (int i = 0; i < args.length; i++) {
                    ps.setString(i+1, Objects.toString(args[i], ""));
                }
            }
            rs = ps.executeQuery();
            rsf.filter(fields, rs);
            log.log(Level.WARNING, String.format("执行时间:%d", System.currentTimeMillis() - begen));
        }catch(SQLException e){
            e.printStackTrace();
            throw new AutoFormException(EXECUTE_ERR);
        }finally {
            if(rs != null)
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            if(ps != null)
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            if(connection != null)
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
        }
    }
 
    @FunctionalInterface
    public static interface ResultSetFilter{
        void filter(String[] fields, ResultSet rs) throws SQLException;
    }
 
    public int update(Sql sql) {
        String sqlStr = sql.getSql();
        Object[] args = sql.getParams();
        try(Connection connection = getConnection();
                PreparedStatement ps = connection.prepareStatement(
                        (sqlStr = updateFilter == null ? sqlStr : updateFilter.filter(sqlStr))
                        )){
            log.log(Level.WARNING, String.format("参数:%s", Arrays.toString(args)));
            log.log(Level.WARNING, String.format("sql:%s", sqlStr));
            for (int i = 0; i < args.length; i++) {
                ps.setString(i+1, Objects.toString(args[i], "")); 
            }
            Integer rowNum = ps.executeUpdate();
            if(sql instanceof Insert){
                ((Insert)sql).setId(getLastInsertId(connection));
            }
            return rowNum;
        }catch(SQLException e){
            e.printStackTrace();
            throw new AutoFormException(EXECUTE_ERR);
        }
    }
 
    public List<ColunmsFieldEntity> showColumn(String sql){
        try(Connection connection = getConnection();
            PreparedStatement ps = connection.prepareStatement(
                    (sql = updateFilter == null ? sql : updateFilter.filter(sql)));
            ResultSet rs = ps.executeQuery()){
            log.log(Level.WARNING, String.format("sql:%s", sql));
            List<ColunmsFieldEntity> list = new ArrayList<>();
            while(rs.next()){
                ColunmsFieldEntity colunmsFieldEntity = new ColunmsFieldEntity();
                colunmsFieldEntity.setField(rs.getString("field"));
                colunmsFieldEntity.setType(rs.getString("type"));
                list.add(colunmsFieldEntity);
            }
            return list;
        }catch(SQLException e){
            e.printStackTrace();
            throw new AutoFormException(EXECUTE_ERR);
        }
    }
 
}