BaseDao.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. package com.uas.eiswms.dao;
  2. import com.uas.eiswms.model.SqlRowList;
  3. import com.uas.eiswms.util.BaseUtil;
  4. import com.uas.eiswms.util.Constant;
  5. import com.uas.eiswms.util.DateUtil;
  6. import com.uas.eiswms.util.MasterManager;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.dao.DataAccessException;
  10. import org.springframework.jdbc.core.CallableStatementCallback;
  11. import org.springframework.jdbc.core.CallableStatementCreator;
  12. import org.springframework.jdbc.core.JdbcTemplate;
  13. import org.springframework.jdbc.support.rowset.SqlRowSet;
  14. import org.springframework.lang.Nullable;
  15. import org.springframework.stereotype.Repository;
  16. import javax.sql.DataSource;
  17. import java.sql.CallableStatement;
  18. import java.sql.Connection;
  19. import java.sql.SQLException;
  20. import java.sql.Timestamp;
  21. import java.util.*;
  22. @Repository("baseDao")
  23. public class BaseDao {
  24. static final String CREATE_SEQ = "CREATE SEQUENCE ?" + // 创建序列
  25. " MINVALUE 1 MAXVALUE 99999999999 INCREMENT BY 1 START WITH 3000 CACHE 20 NOORDER NOCYCLE ";
  26. private JdbcTemplate jdbcTemplate;
  27. private String onLineMaster;
  28. private Logger logger = LoggerFactory.getLogger(BaseDao.class);
  29. public synchronized void setJdbcTemplate(String master){
  30. logger.info("切换到账套:" + master);
  31. DataSource dataSource = MasterManager.getDataSource(master);
  32. if (dataSource == null){
  33. BaseUtil.showError("数据源不存在");
  34. }
  35. if (this.jdbcTemplate == null) {
  36. this.jdbcTemplate = new JdbcTemplate(dataSource);
  37. this.onLineMaster = master;
  38. } else {
  39. if (this.onLineMaster != null && this.onLineMaster.equals(master)){
  40. return;
  41. }
  42. logger.info("进行切换数据源...");
  43. this.onLineMaster = master;
  44. this.jdbcTemplate.setDataSource(dataSource);
  45. }
  46. }
  47. /*public DataSource getDataSource(String master) {
  48. DruidDataSource dataSource = new DruidDataSource();
  49. System.out.println(env.getProperty("spring.datasource."+master+".url"));
  50. System.out.println(env.getProperty("spring.datasource."+master+".username"));
  51. System.out.println(env.getProperty("spring.datasource."+master+".password"));
  52. System.out.println(env.getProperty("spring.datasource."+master+".driver-class-name"));
  53. dataSource.setUrl(env.getProperty("spring.datasource."+master+".url"));
  54. dataSource.setUsername(env.getProperty("spring.datasource."+master+".username"));//用户名
  55. dataSource.setPassword(env.getProperty("spring.datasource."+master+".password"));//密码
  56. dataSource.setDriverClassName(env.getProperty("spring.datasource."+master+".driver-class-name"));
  57. dataSource.setInitialSize(2);//初始化时建立物理连接的个数
  58. dataSource.setMaxActive(20);//最大连接池数量
  59. dataSource.setMinIdle(0);//最小连接池数量
  60. dataSource.setMaxWait(60000);//获取连接时最大等待时间,单位毫秒。
  61. dataSource.setValidationQuery("SELECT 1 FROM DUAL");//用来检测连接是否有效的sql
  62. dataSource.setTestOnBorrow(false);//申请连接时执行validationQuery检测连接是否有效
  63. dataSource.setTestWhileIdle(true);//建议配置为true,不影响性能,并且保证安全性。
  64. dataSource.setPoolPreparedStatements(false);//是否缓存preparedStatement,也就是PSCache
  65. dataSource.setDefaultAutoCommit(true);
  66. return dataSource;
  67. }*/
  68. /**
  69. * 查询结果集
  70. *
  71. * @param sql
  72. * 查询语句
  73. */
  74. public int getCount(String sql, Object...args) {
  75. SqlRowSet rowSet = jdbcTemplate.queryForRowSet(sql, args);
  76. if (rowSet.next()) {
  77. return rowSet.getInt(1);
  78. }
  79. return 0;
  80. }
  81. public void execute(List<String> sqls) {
  82. if (sqls.size() > 0) {
  83. StringBuffer sb = new StringBuffer("begin ");
  84. for (String sql : sqls) {
  85. sb.append("execute immediate '").append(sql.replace("'", "''")).append("';");
  86. }
  87. sb.append("end;");
  88. jdbcTemplate.execute(sb.toString());
  89. }
  90. }
  91. public void execute(String sql) {
  92. jdbcTemplate.execute(sql);
  93. }
  94. public String callProcedure(final String procedureName, final Object...args) {
  95. try {
  96. return jdbcTemplate.execute(new CallableStatementCreator() {
  97. @Override
  98. public CallableStatement createCallableStatement(Connection connection) throws SQLException {
  99. StringBuffer storedProcName = new StringBuffer("{call ");
  100. int i = 0;
  101. storedProcName.append(procedureName + "(");
  102. for (i = 0; i < args.length; i++) {
  103. if (storedProcName.toString().contains("?")) {
  104. storedProcName.append(",");
  105. }
  106. storedProcName.append("?");
  107. }
  108. if (storedProcName.toString().contains("?")) {
  109. storedProcName.append(",");
  110. }
  111. storedProcName.append("?");
  112. storedProcName.append(")}");
  113. CallableStatement cs = connection.prepareCall(storedProcName.toString());
  114. for (i = 0; i < args.length; i++) {
  115. cs.setObject(i + 1, args[i]);
  116. }
  117. cs.registerOutParameter(args.length + 1, java.sql.Types.VARCHAR);
  118. return cs;
  119. }
  120. }, new CallableStatementCallback<String>() {
  121. @Nullable
  122. @Override
  123. public String doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
  124. cs.execute();
  125. return cs.getString(args.length + 1);
  126. }
  127. });
  128. }catch (Exception e){
  129. throw new RuntimeException(e.getMessage());
  130. }
  131. }
  132. public synchronized String sGetMaxNumber(String myTable, int thisType) {
  133. return callProcedure("Sp_GetMaxNumber", new Object[] { myTable, thisType });
  134. }
  135. public int getSeq(String seq) {
  136. SqlRowSet rowSet = jdbcTemplate.queryForRowSet("select " + seq + ".nextval from dual");
  137. if (rowSet.next()) {
  138. return rowSet.getInt(1);
  139. }
  140. return 0;
  141. }
  142. public Object[] getFieldsDataByCondition(String table,String[] fields, String condition) {
  143. StringBuffer sql = new StringBuffer("select ");
  144. sql.append(BaseUtil.parseArray2Str(fields, ","));
  145. sql.append(" from " + table + " where " + condition);
  146. List<Map<String, Object>> list = jdbcTemplate.queryForList(sql.toString());
  147. Iterator<Map<String, Object>> iter = list.iterator();
  148. int length = fields.length;
  149. Object[] results = new Object[length];
  150. Object value = null;
  151. if (iter.hasNext()) {
  152. Map<String, Object> m = iter.next();
  153. for (int i = 0; i < length; i++) {
  154. String upperField = fields[i].toUpperCase();
  155. if (upperField.indexOf(" AS ") > 0) {
  156. upperField = upperField.split(" AS ")[1].trim();
  157. }
  158. value = m.get(upperField);
  159. if (value != null && value.getClass().getSimpleName().toUpperCase().equals("TIMESTAMP")) {
  160. Timestamp time = (Timestamp) value;
  161. try {
  162. value = BaseUtil.parseDateToString(new Date(time.getTime()), "yyyy-MM-dd HH:mm:ss");
  163. } catch (Exception e) {
  164. e.printStackTrace();
  165. }
  166. }
  167. results[i] = value;
  168. }
  169. return results;
  170. }
  171. return null;
  172. }
  173. /**
  174. * 一个字段,多条结果
  175. *
  176. * @param tableName
  177. * 对应要查询的表
  178. * @param field
  179. * 要查询的字段
  180. * @param condition
  181. * 查询条件
  182. * @return field对应的数据
  183. */
  184. public List<Object> getFieldDatasByCondition(String tableName, String field, String condition) {
  185. StringBuffer sb = new StringBuffer("SELECT ");
  186. sb.append(field);
  187. sb.append(" FROM ");
  188. sb.append(tableName);
  189. sb.append(((condition == null || "".equals(condition)) ? "" : (" WHERE " + condition)));
  190. SqlRowSet srs = jdbcTemplate.queryForRowSet(sb.toString());
  191. List<Object> list = new ArrayList<Object>();
  192. while (srs.next()) {
  193. list.add(srs.getObject(1));
  194. }
  195. return list;
  196. }
  197. /**
  198. * 一个字段,一条结果
  199. *
  200. * @param tableName
  201. * 对应要查询的表
  202. * @param field
  203. * 要查询的字段
  204. * @param condition
  205. * 查询条件
  206. * @return field对应的数据
  207. */
  208. public Object getFieldDataByCondition(String tableName, String field, String condition) {
  209. StringBuffer sql = new StringBuffer("SELECT ");
  210. sql.append(field);
  211. sql.append(" FROM ");
  212. sql.append(tableName);
  213. sql.append(" WHERE ");
  214. sql.append(condition);
  215. SqlRowSet srs = jdbcTemplate.queryForRowSet(sql.toString());
  216. if (srs.next()) {
  217. return srs.getObject(1);
  218. } else {
  219. return null;
  220. }
  221. }
  222. /**
  223. * 多个字段,多条结果
  224. *
  225. * @param tableName
  226. * 对应要查询的表
  227. * @param fields
  228. * 要查询的字段集合
  229. * @param condition
  230. * 查询条件
  231. * @return fields对应的数据
  232. */
  233. public List<Object[]> getFieldsDatasByCondition(String tableName, String[] fields, String condition) {
  234. StringBuffer sql = new StringBuffer("SELECT ");
  235. sql.append(BaseUtil.parseArray2Str(fields, ","));
  236. sql.append(" FROM ");
  237. sql.append(tableName);
  238. sql.append(" WHERE ");
  239. sql.append(condition);
  240. List<Map<String, Object>> list = jdbcTemplate.queryForList(sql.toString());
  241. Iterator<Map<String, Object>> iter = list.iterator();
  242. List<Object[]> datas = new ArrayList<Object[]>();
  243. Object value = null;
  244. Map<String, Object> m = null;
  245. Object[] results = null;
  246. int length = fields.length;
  247. while (iter.hasNext()) {
  248. results = new Object[length];
  249. m = iter.next();
  250. for (int i = 0; i < length; i++) {
  251. value = m.get(fields[i].toUpperCase());
  252. if (value != null && value.getClass().getSimpleName().toUpperCase().equals("TIMESTAMP")) {
  253. Timestamp time = (Timestamp) value;
  254. try {
  255. value = BaseUtil.parseDateToString(new Date(time.getTime()), "yyyy-MM-dd HH:mm:ss");
  256. } catch (Exception e) {
  257. e.printStackTrace();
  258. }
  259. }
  260. results[i] = value;
  261. }
  262. datas.add(results);
  263. }
  264. return datas;
  265. }
  266. public synchronized boolean execute(String sql, Object... objs) {
  267. try {
  268. jdbcTemplate.update(sql, objs);
  269. return true;
  270. } catch (Exception e) {
  271. BaseUtil.showError(e.getMessage());
  272. return false;
  273. }
  274. }
  275. public boolean isDBSetting(String caller, String code) {
  276. Integer i = jdbcTemplate.queryForObject("select count(1) from configs where data =1 and caller='" + caller + "' and code='" + code + "'",
  277. Integer.class);
  278. if (i >0) {
  279. return true;
  280. } else
  281. return false;
  282. }
  283. public JdbcTemplate getJdbcTemplate() {
  284. return jdbcTemplate;
  285. }
  286. public boolean isProdIn(String caller) {
  287. int count = getCount("select count(1) from documentsetup where ds_table='" + caller + "' and ds_inorout in ('IN','-OUT')");
  288. if (count > 0) {
  289. return true;
  290. }else return false;
  291. }
  292. public boolean isDBSetting(String inOverNow) {
  293. return isDBSetting("sys", inOverNow);
  294. }
  295. /**
  296. * 查询结果集
  297. *
  298. * @param sql
  299. * 查询语句
  300. * @param arg
  301. * 参数
  302. */
  303. public SqlRowList queryForRowSet(String sql, Object arg) {
  304. SqlRowList rs = new SqlRowList();
  305. rs.setResultList(getJdbcTemplate().queryForList(sql, arg));
  306. return rs;
  307. }
  308. /**
  309. * 查询结果集
  310. *
  311. * @param sql
  312. * 查询语句
  313. */
  314. public SqlRowList queryForRowSet(String sql) {
  315. SqlRowList rs = new SqlRowList();
  316. rs.setResultList(getJdbcTemplate().queryForList(sql));
  317. return rs;
  318. }
  319. public Object getBatchcode(String caller) {
  320. if (isProdIn(caller)) {
  321. return callProcedure("utl_rseq", "BatchCode", "/yyMMdd/5");
  322. }
  323. return null;
  324. }
  325. public String getDBSetting(String caller, String code) {
  326. Object data = getFieldDataByCondition("configs", "data", "caller='" + caller + "' and code='" + code + "'");
  327. if (data != null) {
  328. return data.toString();
  329. }
  330. return null;
  331. }
  332. public String getDBSetting(String defaultCurrency) {
  333. return getDBSetting("sys", defaultCurrency);
  334. }
  335. public boolean checkIf(String tableName, String condition) {
  336. int i = 0;
  337. StringBuffer sql = new StringBuffer("SELECT count(1) FROM ");
  338. sql.append(tableName);
  339. sql.append(" WHERE ");
  340. sql.append(condition);
  341. SqlRowList srs = queryForRowSet(sql.toString());
  342. if (srs.next()) {
  343. i = srs.getInt(1);
  344. }
  345. if (i > 0)return true;
  346. else return false;
  347. }
  348. public double getSummaryByField(String summaryField, String tablename, String condition) {
  349. SqlRowList rs = queryForRowSet("SELECT sum(nvl(" + summaryField + ",0)) FROM " + tablename + " WHERE " + condition);
  350. if (rs.next()) {
  351. return rs.getGeneralDouble(1, 6);
  352. }
  353. return 0.0;
  354. }
  355. /**
  356. * 根据物料中的有效期天数更新有效期止
  357. */
  358. public void getEndDate(String caller, Object id) {
  359. SqlRowList rs = queryForRowSet("select ds_inorout from DOCUMENTSETUP where ds_table=?", caller);
  360. if (rs.next()) {
  361. String Code = rs.getObject("ds_inorout").toString();
  362. if (Code.equals("IN") || Code.equals("-OUT")) {
  363. execute("update prodiodetail set pd_replydate=pd_prodmadedate + (select nvl(pr_validdays,0) from product where pd_prodcode=pr_code) where pd_piid=? and pd_prodmadedate is not null",
  364. id);
  365. }
  366. }
  367. }
  368. /**
  369. * 查询结果集
  370. *
  371. * @param sql
  372. * 查询语句
  373. * @param args
  374. * 参数
  375. */
  376. public SqlRowList queryForRowSet(String sql, Object... args) {
  377. SqlRowList rs = new SqlRowList();
  378. rs.setResultList(getJdbcTemplate().queryForList(sql, args));
  379. return rs;
  380. }
  381. public void updateByCondition(String tableName, String update, String condition) {
  382. StringBuffer sb = new StringBuffer("UPDATE ");
  383. sb.append(tableName);
  384. sb.append(" SET ");
  385. sb.append(update);
  386. sb.append(" WHERE ");
  387. sb.append(condition);
  388. execute(sb.toString());
  389. }
  390. /**
  391. * 调用存储过程 无返回值
  392. *
  393. * @param procedureName
  394. * 存储过程名称
  395. * @param args
  396. * 参数
  397. */
  398. public void procedure(String procedureName, Object[] args) {
  399. StringBuffer sql = new StringBuffer("{call ").append(procedureName).append("(");
  400. for (int i = 0; i < args.length; i++) {
  401. if (i > 0) {
  402. sql.append(",");
  403. }
  404. sql.append("?");
  405. }
  406. sql.append(")}");
  407. getJdbcTemplate().update(sql.toString(), args);
  408. }
  409. public boolean isOut(String caller) {
  410. int count = getCount("select count(1) from documentsetup where ds_table='" + caller + "' and ds_inorout in ('-IN','OUT')");
  411. if (count > 0) {
  412. return true;
  413. }else return false;
  414. }
  415. /**
  416. * 修改单据为已审核(包括审核人+审核日期)
  417. *
  418. * @param tableName
  419. * @param condition
  420. * @param statusField
  421. * @param statusCodeField
  422. * @param auditdateField
  423. * @param auditorField
  424. */
  425. public void audit(String tableName, String condition, String statusField, String statusCodeField, String auditdateField,
  426. String auditorField, String name) {
  427. updateByCondition(tableName, statusCodeField + "='AUDITED'," + statusField + "='已审核',"
  428. + auditdateField + "=" + DateUtil.parseDateToOracleString(Constant.YMD_HMS, new Date()) + "," + auditorField + "='"
  429. +name+"'", condition);
  430. }
  431. public int getSeqId(String seq) {
  432. try {
  433. /* if ("true".equals(BaseUtil.getXmlSetting("group"))) {
  434. boolean isBase = checkIf("basedataset", "upper(bds_sequence)=upper('" + seq + "') and nvl(bds_editable,0)=1");
  435. if (isBase) {
  436. // 集团版基础资料(客户,供应商...)统一到资料中心取号
  437. String dataCenter = BaseUtil.getXmlSetting("dataSob");
  438. seq = dataCenter + "." + seq;
  439. }
  440. }*/
  441. String sql = "select " + seq + ".nextval from dual";
  442. SqlRowList rs = queryForRowSet(sql);
  443. if (rs.next()) {
  444. return rs.getInt(1);
  445. } else {// 如果不存在就创建序列
  446. int count = getCountByCondition("user_sequences", "Sequence_Name='" + seq.toUpperCase() + "'");
  447. if (count == 0)
  448. getJdbcTemplate().execute(CREATE_SEQ.replace("?", seq));
  449. return getSeqId(seq);
  450. }
  451. } catch (Exception e) {
  452. int count = getCountByCondition("user_sequences", "Sequence_Name='" + seq.toUpperCase() + "'");
  453. if (count == 0)
  454. getJdbcTemplate().execute(CREATE_SEQ.replace("?", seq));
  455. return getSeqId(seq);
  456. }
  457. }
  458. /**
  459. * @param tableName
  460. * 对应要查询的表
  461. * @param condition
  462. * 查询条件
  463. * @return Count
  464. */
  465. public int getCountByCondition(String tableName, String condition) {
  466. StringBuffer sql = new StringBuffer("SELECT count(1) FROM ");
  467. sql.append(tableName);
  468. sql.append(" WHERE ");
  469. sql.append(condition);
  470. SqlRowList srs = queryForRowSet(sql.toString());
  471. if (srs.next()) {
  472. return srs.getInt(1);
  473. } else {
  474. try {
  475. throw new Exception("Condition:" + condition + " is wrong!");
  476. } catch (Exception e) {
  477. return -1;
  478. }
  479. }
  480. }
  481. }