1
|
package vldc.aswi.database;
|
2
|
|
3
|
import org.springframework.context.annotation.Bean;
|
4
|
import org.springframework.dao.DataAccessException;
|
5
|
import org.springframework.jdbc.core.JdbcTemplate;
|
6
|
import org.springframework.jdbc.core.ResultSetExtractor;
|
7
|
import org.springframework.jdbc.core.RowMapper;
|
8
|
import org.springframework.stereotype.Component;
|
9
|
import vldc.aswi.model.table.TableColumn;
|
10
|
|
11
|
import java.sql.ResultSet;
|
12
|
import java.sql.ResultSetMetaData;
|
13
|
import java.sql.SQLException;
|
14
|
import java.util.ArrayList;
|
15
|
import java.util.HashMap;
|
16
|
import java.util.List;
|
17
|
import java.util.Map;
|
18
|
|
19
|
@Component
|
20
|
public class DatabaseInterface {
|
21
|
|
22
|
private JdbcTemplate jdbcTemplate = null;
|
23
|
|
24
|
public DatabaseInterface(JdbcTemplate jdbcTemplate) {
|
25
|
this.jdbcTemplate = jdbcTemplate;
|
26
|
}
|
27
|
|
28
|
public Map<String, TableColumn> executeQueryAndReturnTableColumns(String sqlQuery) {
|
29
|
return jdbcTemplate.query(
|
30
|
sqlQuery,
|
31
|
new ResultSetExtractor<Map<String, TableColumn>>() {
|
32
|
@Override
|
33
|
public Map<String, TableColumn> extractData(ResultSet resultSet) throws SQLException, DataAccessException {
|
34
|
List<TableColumn> tableColumnsList = new ArrayList<>();
|
35
|
|
36
|
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
|
37
|
int columnCount = resultSetMetaData.getColumnCount();
|
38
|
|
39
|
// The column count starts from 1.
|
40
|
for (int i = 1; i <= columnCount; i++ ) {
|
41
|
String columnName = resultSetMetaData.getColumnName(i);
|
42
|
tableColumnsList.add(new TableColumn(columnName));
|
43
|
}
|
44
|
|
45
|
while(resultSet.next()) {
|
46
|
for (int i = 1; i <= columnCount; i++) {
|
47
|
tableColumnsList.get(i - 1).addValue(resultSet.getString(i));
|
48
|
}
|
49
|
}
|
50
|
|
51
|
Map<String, TableColumn> tableColumnMap = new HashMap<>();
|
52
|
|
53
|
for (TableColumn column : tableColumnsList) {
|
54
|
tableColumnMap.put(column.getName(), column);
|
55
|
}
|
56
|
|
57
|
return tableColumnMap;
|
58
|
}
|
59
|
}
|
60
|
);
|
61
|
}
|
62
|
}
|