package springboot_001.dao;
import springboot_001.entity.Page;
import java.io.Closeable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
public interface Dao {
void close() throws Exception;
void commit() throws Exception;
void rollback() throws Exception;
Connection currentConnection() throws Exception;
/**
* 新增对象
*
* @param collectionName 集合名称
* @param obj 要添加的对象 可以是Map 或 Map<String,Object>
* @return 受影响的行数
*/
// int insert(String collectionName, Map<String, Object> obj) throws Exception;
// int remove(String
// collectionName,Map<String,Object><String,Object> obj);
// int remove(String collectionName,String jsonString);
/**
* 删除对象
*
* @param collectionName 集合名称
* @param id 数据主键值
* @return 受影响的行数
*/
int remove(String collectionName, String id) throws Exception;
/**
* 修改对象
*
* @param collectionName 集合名称
* @param newObj 要修改的对象 可以是Map 或 Map<String,Object>
* @return 受影响的行数
*/
// int update(String collectionName, Map<String, Object> newObj) throws Exception;
/**
* 查询一个对象
*
* @param collectionName 集合名称
* @param obj 查询条件 可以是Map 或 Map<String,Object> {"a":1,"b":"test"} 表示 where a = 1 and b = "test"
* @return 查询到得对象 Map
*/
Map<String, Object> findOne2Map(String collectionName, Map<String, Object> obj, String[] fields) throws Exception;
/**
* 根据ID查询一个对象
*
* @param collectionName 集合名称
* @param id 数据主键值
* @return 查询到得对象 Map
* @throws Exception
*/
Map<String, Object> findById2Map(String collectionName, String id, String[] fields) throws Exception;
/**
* 查询集合下所有记录
*
* @param collectionName 集合名称
* @param orderBy 排序规则 Map {age :1,name:-1} order by age asc , name desc
* @return 查询到得对象 Map
* @throws Exception
*/
List<Map<String, Object>> findAll2Map(String collectionName, Map<String, Object> p, Map<String, Object> orderBy, String[] fields) throws Exception;
/**
* 查询集合下所有记录
*
* @param collectionName 集合名称
* @param orderBy 排序规则 Map {age :1,name:-1} order by age asc , name desc
* @return 查询到得对象 Map
* @throws Exception
*/
Page findPage(String collectionName, Map<String, Object> p, Map<String, Object> orderBy, String[] fields, int pageIndex, int pageSize) throws Exception;
/**
* 查询集合总记录数
*
* @param collectionName 集合名称
* @return 集合总记录数
* @throws Exception
*/
long findCount(String collectionName, Map<String, Object> params) throws Exception;
/**
* 移除集合
*
* @param collectionName
*/
// void removeAll(String collectionName) throws Exception;
Double sum(String collectionName, Map<String, Object> params, String sumField) throws Exception;
int saveOrUpdate(String entityName, Map<String, Object> values) throws Exception;
List<Map<String, Object>> queryListBySql(String sql, List<Object> params) throws Exception;
Page queryPageBySql(String sql, List<Object> params, int pageIndex, int pageSize) throws Exception;
Integer queryCountBySql(String sql, List params) throws SQLException;
}
package springboot_001.dao.oracle;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import springboot_001.dao.Dao;
import springboot_001.utils.ConnectionHolder;
import java.sql.*;
import java.util.*;
@Slf4j
public abstract class OracleBaseDaoImpl implements Dao {
@Autowired
protected ConnectionHolder connectionHolder;
@Override
public void close() {
connectionHolder.close();
}
@Override
public void commit() throws SQLException {
connectionHolder.get().commit();
}
@Override
public void rollback() throws SQLException {
connectionHolder.get().rollback();
}
@Override
public Connection currentConnection() {
return connectionHolder.get();
}
public int exeSql(String sql, List<Object> params) throws SQLException {
ArrayList<Object> n = new ArrayList<Object>();
if (params != null) {
n.addAll(params);
}
long t = System.currentTimeMillis();
try (PreparedStatement stmt = connectionHolder.get().prepareStatement(sql)) {
if (n.size() > 0) {
int i = 0;
for (Object object : n) {
if (object instanceof net.sf.json.JSONNull) {
object = null;
}
if (object instanceof JSON) {
object = object.toString();
}
if (object instanceof Timestamp) {
stmt.setTimestamp(++i, (Timestamp) object);
} else if (object instanceof java.util.Date) {
stmt.setTimestamp(++i, new Timestamp(((java.util.Date) object).getTime()));
} else {
stmt.setObject(++i, object);
}
log.debug("Param " + i + ": " + object);
}
}
int i = stmt.executeUpdate();
return i;
} catch (Exception e) {
e.printStackTrace();
return 0;
} finally {
log.debug("-EXE SQL: " + (System.currentTimeMillis() - t) + "ms, " + sql);
}
}
protected Set<String> getTableColumns(String collectionName) throws SQLException {
String tableSchemaSql = "SELECT * FROM " + collectionName + " WHERE ROWNUM = 0";
Set<String> columns = new HashSet<>();
Connection conn = connectionHolder.get();
try (Statement st = conn.createStatement()) {
try (ResultSet rs = st.executeQuery(tableSchemaSql)) {
ResultSetMetaData rsm = rs.getMetaData();
for (int i = 1; i <= rsm.getColumnCount(); i++) {
columns.add(rsm.getColumnName(i));
}
}
}
return columns;
}
}
package springboot_001.dao.oracle;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import springboot_001.entity.Page;
import springboot_001.exception.BadRequestException;
import springboot_001.utils.DBUtils;
import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
@Slf4j
@Component
public class OracleDaoImpl extends OracleBaseDaoImpl {
@Override
public int remove(String collectionName, String id) throws Exception {
String sql = String.format("delete from %s where id = '%s'", collectionName, id);
return this.exeSql(sql, null);
}
private int update(String collectionName, Map<String, Object> newObj) throws Exception {
Set<String> columns = this.getTableColumns(collectionName);
String id = (String) newObj.get("id");
if (id == null) {
id = (String) newObj.get("ID");
}
StringBuffer sb = new StringBuffer("update ").append(collectionName).append(" set ");
List<Object> values = new ArrayList<>();
for (Map.Entry<String, Object> entry : newObj.entrySet()) {
if (!columns.contains(entry.getKey()) &&
!columns.contains(entry.getKey().toUpperCase())) {
continue;
}
if (entry.getKey().toUpperCase().equals("ID")) {
continue;
}
sb.append(entry.getKey()).append(" = ?,");
values.add(entry.getValue());
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append(" where id = ?");
values.add(id);
return this.exeSql(sb.toString(), values);
}
private int insert(String collectionName, Map<String, Object> newObj) throws Exception {
Set<String> columns = this.getTableColumns(collectionName);
StringBuffer sb = new StringBuffer("insert into ").append(collectionName).append("( ");
List<Object> values = new ArrayList<>();
for (Map.Entry<String, Object> entry : newObj.entrySet()) {
if (!columns.contains(entry.getKey()) &&
!columns.contains(entry.getKey().toUpperCase())) {
continue;
}
sb.append(entry.getKey()).append(",");
values.add(entry.getValue());
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append(" ) values ( ");
for (Object o : values) {
sb.append("?,");
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append(" )");
return this.exeSql(sb.toString(), values);
}
@Override
public Map<String, Object> findOne2Map(String collectionName, Map<String, Object> obj, String[] fields) throws Exception {
String selectFields = genSelectFields(fields);
StringBuffer sb = new StringBuffer("select ").append(selectFields).append(" from ")
.append(collectionName).append(" where 1 = 1 ");
List<Object> values = new ArrayList<>();
for (Map.Entry<String, Object> entry : obj.entrySet()) {
String whereStr = parseWhereCondition(entry.getKey(), entry.getValue(), values);
sb.append(whereStr);
}
List<Map<String, Object>> list = this.queryListBySql(sb.toString(), values);
if (list.size() == 0) {
return null;
} else if (list.size() > 1) {
throw new BadRequestException("存在多个结果集");
} else {
return list.get(0);
}
}
private String parseWhereCondition(String key, Object value, List<Object> values) {
StringBuffer sb = new StringBuffer();
if (key.startsWith("${like}")) {
sb.append(" and ").append(key.replace("${like}", ""))
.append(" like ? ");
values.add("%" + value + "%");
} else if (key.startsWith("${>=}") || key.startsWith("${<=}") || key.startsWith("${>}") ||
key.startsWith("${<}")) {
String exp = key.substring(2, key.indexOf("}"));
sb.append(" and ").append(key, key.indexOf("}") + 1, key.length())
.append(exp).append(" ? ");
values.add(value);
} else {
sb.append(" and ").append(key).append(" = ? ");
values.add(value);
}
return sb.toString();
}
private String genSelectFields(String[] fields) {
if (fields == null || fields.length == 0) {
return "*";
} else {
return StringUtils.join(fields, ",");
}
}
@Override
public Map<String, Object> findById2Map(String collectionName, String id, String[] fields) throws Exception {
String selectFields = genSelectFields(fields);
StringBuffer sb = new StringBuffer("select ").append(selectFields).append(" from ")
.append(collectionName).append(" where id = '" + id + "' ");
List<Map<String, Object>> list = this.queryListBySql(sb.toString(), null);
if (list.size() == 0) {
throw new BadRequestException("没有符合条件的结果集");
} else if (list.size() > 1) {
throw new BadRequestException("存在多个结果集");
} else {
return list.get(0);
}
}
@Override
public List<Map<String, Object>> findAll2Map(String collectionName, Map<String, Object> p, Map<String, Object> orderBy, String[] fields) throws Exception {
String selectFields = genSelectFields(fields);
StringBuffer sb = new StringBuffer("select ").append(selectFields).append(" from ")
.append(collectionName).append(" where 1 = 1 ");
List<Object> values = new ArrayList<>();
if (p != null && p.size() > 0) {
for (Map.Entry<String, Object> entry : p.entrySet()) {
sb.append(parseWhereCondition(entry.getKey(), entry.getValue(), values));
}
}
String orderByStr = this.genOrderByStr(orderBy);
sb.append(orderByStr);
List<Map<String, Object>> list = this.queryListBySql(sb.toString(), values);
return list;
}
@Override
public Page findPage(String collectionName, Map<String, Object> p, Map<String, Object> orderBy, String[] fields, int pageIndex, int pageSize) throws Exception {
long count = findCount(collectionName, p);
Page page = new Page();
page.setPageSize(pageSize);
page.setTotalNumber((int) count);
page.setPageIndex(pageIndex);
int start = page.getStart();
int end = page.getEnd();
String selectFields = genSelectFields(fields);
String orderByStr = genOrderByStr(orderBy);
StringBuffer sb = new StringBuffer("SELECT t.* FROM ( " +
"SELECT t.*,ROWNUM AS rn FROM( select ").append(selectFields).append(" from ")
.append(collectionName).append(" where 1 = 1 ");
List<Object> values = new ArrayList<>();
if (p != null) {
for (Map.Entry<String, Object> entry : p.entrySet()) {
sb.append(parseWhereCondition(entry.getKey(), entry.getValue(), values));
}
}
sb.append(orderByStr).append(") t ) t WHERE t.rn > " + start + " AND t.rn <= " + end + " ");
List<Map<String, Object>> list = this.queryListBySql(sb.toString(), values);
page.setList(list);
return page;
}
@Override
public List<Map<String, Object>> queryListBySql(String sql, List<Object> params) throws Exception {
//复制参数列表
ArrayList<Object> n = new ArrayList<>();
if (params != null) {
n.addAll(params);
}
long t = System.currentTimeMillis();
try (PreparedStatement stmt = connectionHolder.get().prepareStatement(sql)) {
int i = 0;
for (Object object : n) {
log.debug("param" + i + ": " + object);
stmt.setObject(++i, object);
}
try (ResultSet re = stmt.executeQuery()) {
List<Map<String, Object>> reList = DBUtils.resultSetToList(re);
return reList;
}
} finally {
log.debug("-QUERY SQL: " + (System.currentTimeMillis() - t) + "ms, " + sql);
}
}
@Override
public Integer queryCountBySql(String sql, List params) throws SQLException {
if (params == null) {
params = new ArrayList();
}
String countSql = "select count(*) as CC from ( " + sql + " ) ";
Integer totalNum = 0;
try (PreparedStatement stmt = connectionHolder.get().prepareStatement(countSql)) {
int i = 0;
for (Object object : params) {
stmt.setObject(++i, object);
}
try (ResultSet re = stmt.executeQuery()) {
List<Map<String, Object>> reList = DBUtils.resultSetToList(re);
totalNum = Integer.valueOf(reList.get(0).get("CC").toString());
}
}
return totalNum;
}
@Override
public Page queryPageBySql(String sql, List<Object> params, int pageIndex, int pageSize) throws Exception {
String countSql = "select count(*) as CC from ( " + sql + " ) ";
int totalNum = 0;
try (PreparedStatement stmt = connectionHolder.get().prepareStatement(countSql)) {
int i = 0;
for (Object object : params) {
stmt.setObject(++i, object);
}
try (ResultSet re = stmt.executeQuery()) {
List<Map<String, Object>> reList = DBUtils.resultSetToList(re);
totalNum = Integer.parseInt(reList.get(0).get("CC").toString());
}
}
Page page = new Page();
page.setPageSize(pageSize);
page.setTotalNumber(totalNum);
page.setPageIndex(pageIndex);
long t = System.currentTimeMillis();
String pageSql = " SELECT t.* FROM ( SELECT t.*,ROWNUM AS rn FROM ("
+ sql + ") t ) t WHERE t.rn > " + page.getStart() + " AND t.rn <= " + page.getEnd();
try (PreparedStatement stmt = connectionHolder.get().prepareStatement(pageSql)) {
int i = 0;
for (Object object : params) {
stmt.setObject(++i, object);
log.debug("param" + i + ": " + object);
}
try (ResultSet re = stmt.executeQuery()) {
List<Map<String, Object>> reList = DBUtils.resultSetToList(re);
page.setList(reList);
}
}finally {
log.debug("-QUERY SQL: " + (System.currentTimeMillis() - t) + "ms, " + pageSql);
}
return page;
}
private String genOrderByStr(Map<String, Object> orderBy) {
StringBuffer sb = new StringBuffer();
if (orderBy != null && orderBy.size() > 0) {
sb.append(" order by ");
for (Map.Entry<String, Object> entry : orderBy.entrySet()) {
String value = entry.getValue().toString();
if (!"1".equals(value) && !"-1".equals(value)) {
throw new BadRequestException("排序字段设置错误 ==== " + entry.toString());
}
if ("1".equals(value) || "-1".equals(value)) {
sb.append(entry.getKey());
sb.append("1".equals(value) ? " ASC" : " DESC").append(",");
}
}
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
@Override
public long findCount(String collectionName, Map<String, Object> params) throws Exception {
StringBuffer sb = new StringBuffer("select count(1) as CC from ")
.append(collectionName).append(" where 1 = 1 ");
List<Object> values = new ArrayList<>();
if (params != null && params.size() > 0) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
sb.append(parseWhereCondition(entry.getKey(), entry.getValue(), values));
}
}
List<Map<String, Object>> list = this.queryListBySql(sb.toString(), values);
return ((BigDecimal) list.get(0).get("CC")).longValue();
}
@Override
public Double sum(String collectionName, Map<String, Object> params, String sumField) throws Exception {
StringBuffer sb = new StringBuffer("select sum(" + sumField + ") as SS from ")
.append(collectionName).append(" where 1 = 1 ");
List<Object> values = new ArrayList<>();
if (params != null && params.size() > 0) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
sb.append(" and ").append(entry.getKey()).append(" = ? ");
values.add(entry.getValue());
}
}
List<Map<String, Object>> list = this.queryListBySql(sb.toString(), values);
return ((BigDecimal) list.get(0).get("SS")).doubleValue();
}
@Override
public int saveOrUpdate(String entityName, Map<String, Object> values) throws Exception {
if (values.containsKey("ID") || values.containsKey("id")) {
String id = (String) values.get("id");
if (id == null) {
id = (String) values.get("ID");
}
Map<String, Object> p = new HashMap<>();
p.put("ID", id);
Map<String, Object> row = this.findOne2Map(entityName, p, null);
if (row == null) {
return this.insert(entityName, values);
} else {
return this.update(entityName, values);
}
} else {
values.put("ID", UUID.randomUUID().toString());
return this.insert(entityName, values);
}
}
private String camelNameToColmun(String name) {
if (StringUtils.isBlank(name)) {
return "";
}
char[] nameList = name.toCharArray();
StringBuffer sb = new StringBuffer();
for (char c : nameList) {
if (c >= 'A' && c <= 'Z') {
sb.append("_" + c);
continue;
}
sb.append(c);
}
return sb.toString();
}
}
package springboot_001.dao.oracle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import springboot_001.utils.ConnectionHolder;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
@Component()
public class TableSchemaDao {
@Autowired
private ConnectionHolder connectionHolder;
public void dropTable(String tableName) throws Exception {
Connection c = connectionHolder.get();
String dropTableSql = String.format("DROP TABLE %s",
tableName);
try (Statement s = c.createStatement()) {
s.execute(dropTableSql);
}
}
public void modifyColumn(String tableName, String columnName, String type) throws Exception {
Connection c = connectionHolder.get();
String createColumnSql = String.format("ALTER TABLE %s modify (%s %s)",
tableName, columnName, type);
try (Statement s = c.createStatement()) {
s.execute(createColumnSql);
}
}
public void dropColumn(String tableName, String columnName) throws Exception {
Connection c = connectionHolder.get();
String createColumnSql = String.format("ALTER TABLE %s drop (%s)",
tableName, columnName);
try (Statement s = c.createStatement()) {
s.execute(createColumnSql);
}
}
public void createColumn(String tableName, String columnName, String type) throws Exception {
Connection c = connectionHolder.get();
String createColumnSql = String.format("ALTER TABLE %s ADD (%s %s)",
tableName, columnName, type);
try (Statement s = c.createStatement()) {
s.execute(createColumnSql);
}
}
public void createTable(String tableName) throws Exception {
Connection c = connectionHolder.get();
String createTableSql = " create TABLE " + tableName + " (ID VARCHAR2(64) PRIMARY KEY,INSTANCE_ID varchar2(64))";
try (Statement s = c.createStatement()) {
s.execute(createTableSql);
}
}
public boolean checkTableExists(String tableName) throws Exception {
String tableExistsSql = "select count(1) from user_tables where table_name = upper('" + tableName + "')";
int i = getCount(tableExistsSql);
if (i == 0) {
return false;
} else {
return true;
}
}
public boolean checkColumnExists(String tableName, String columnName) throws Exception {
String columnExistsSql = "select count(1) FROM USER_TAB_COLUMNS where TABLE_NAME = upper('"
+ tableName + "') AND COLUMN_NAME = upper('" + columnName + "')";
int i = getCount(columnExistsSql);
if (i == 0) {
return false;
} else {
return true;
}
}
/**
* 修改表明
*
* @param oldTableName 原来的表名
* @param newTableName 新的表名
* @throws Exception
*/
public void alterTableName(String oldTableName, String newTableName) throws Exception {
Connection c = connectionHolder.get();
String alterTble = "alter table " + oldTableName + " rename to " + newTableName;
try (Statement s = c.createStatement()) {
s.execute(alterTble);
}
}
private int getCount(String sql) throws Exception {
Connection c = connectionHolder.get();
try (Statement s = c.createStatement()) {
try (ResultSet rs = s.executeQuery(sql)) {
rs.next();
int i = rs.getInt(1);
return i;
}
}
}
}
package springboot_001.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public final class DBUtils {
public static List<Map<String, Object>> resultSetToList(ResultSet rs) throws SQLException {
List<Map<String, Object>> list = new ArrayList<>();
ResultSetMetaData md = rs.getMetaData();
while (rs.next()) {
Map<String, Object> map = new LinkedHashMap<>();
for (int cIndex = 1; cIndex <= md.getColumnCount(); cIndex++) {
String cName = md.getColumnName(cIndex);
if (md.getColumnType(cIndex) == Types.DATE) {
Date d = rs.getDate(cName);
if (d != null) {
map.put(cName, new java.util.Date(d.getTime()));
}
} else if (md.getColumnType(cIndex) == Types.TIMESTAMP) {
Timestamp timestamp = rs.getTimestamp(cName);
java.util.Date d = null;
if (timestamp!=null) {
d = new java.util.Date(timestamp.getTime());
}
if (d != null) {
map.put(cName, d);
}
} else {
map.put(cName, rs.getObject(cName));
}
}
list.add(map);
}
return list;
}
public static String clobToStr(Clob clob) throws Exception {
String reString = "";
java.io.Reader is = clob.getCharacterStream();// 得到流
BufferedReader br = new BufferedReader(is);
String s = br.readLine();
StringBuffer sb = new StringBuffer();
while (s != null) {// 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
sb.append(s);
s = br.readLine();
}
reString = sb.toString();
return reString;
}
}
使用方法
@Autowired
Dao dao;
删除
dao.currentConnection().createStatement().executeUpdate("delete from T_OWS_ACTUALTIME_RFC");
查询
List param = new ArrayList();
StringBuffer sb = new StringBuffer("select t1.product_line_chn from T_OWS_LICENSE_PRODUCT_LINE \n" +
"t left join T_OWS_PRODUCT_LINE_mapping_cn t1 on \n" +
"t.product_line=t1.product_line_eng where t.product=? and rownum=1");
param.add(productType);
List<Map<String, Object>> listquery = dao.queryListBySql(sb.toString(), param);
分页用法:
Page page = dao.queryPageBySql(sb.toString(), sqlParams, pageNumer, pageSize);
for (Map<String, Object> liMap : page.getList()) {
String current_operator = (String) liMap.get("CURRENT_OPERATOR");
String founder = (String) liMap.get("FOUNDER");
List<Object> p = new ArrayList<>();
p.add(current_operator);
p.add(founder);
String sql = "select USER_NAME,user_agentid from T_OWS_USER where user_agentid = ? or user_agentid = ?";
List<Map<String, Object>> maps = dao.queryListBySql(sql, p);