在javaweb开发中,免不了一次业务操作会设计到几个表之间的添加,获取主键插入子表

1.主表使用单条插入,获取id,自表获取id进行批量插入最后完成操作


SimpleJdbcTemplateDaoImpl .class 

  1. /**
  2. * Copyright (C) DADICOM, Inc.
  3. */
  4. package com.dadi.oa.dao.impl;
  5. import java.sql.CallableStatement;
  6. import java.sql.Connection;
  7. import java.sql.PreparedStatement;
  8. import java.sql.ResultSet;
  9. import java.sql.ResultSetMetaData;
  10. import java.sql.SQLException;
  11. import java.sql.Statement;
  12. import java.util.ArrayList;
  13. import java.util.HashMap;
  14. import java.util.List;
  15. import java.util.Map;
  16. import org.springframework.dao.DataAccessException;
  17. import org.springframework.jdbc.core.BatchPreparedStatementSetter;
  18. import org.springframework.jdbc.core.CallableStatementCallback;
  19. import org.springframework.jdbc.core.CallableStatementCreator;
  20. import org.springframework.jdbc.core.JdbcTemplate;
  21. import org.springframework.jdbc.core.PreparedStatementCreator;
  22. import org.springframework.jdbc.core.support.JdbcDaoSupport;
  23. import org.springframework.jdbc.support.GeneratedKeyHolder;
  24. import org.springframework.jdbc.support.KeyHolder;
  25. import com.dadi.oa.dao.SimpleJdbcTemplateDao;
  26. /**
  27. * @author shensheng
  28. *
  29. * Mar 15, 2009 7:00:16 PM
  30. */
  31. public class SimpleJdbcTemplateDaoImpl extends JdbcDaoSupport implements SimpleJdbcTemplateDao {
  32. /* (non-Javadoc)
  33. * @see com.dadi.chr.dao.SimpleJdbcTemplateDao#queryForList(java.lang.String)
  34. */
  35. public List<Map<String, Object>> queryForList(String sql) throws Exception {
  36. return this.getJdbcTemplate().queryForList(sql);
  37. }
  38. public List<Map<String, Object>> queryForList(String sql,Object...params){
  39. return this.getJdbcTemplate().queryForList(sql, params);
  40. }
  41. /* (non-Javadoc)
  42. * @see com.dadi.chr.dao.SimpleJdbcTemplateDao#update(java.lang.String)
  43. */
  44. public Integer update(String sql) throws Exception {
  45. return this.getJdbcTemplate().update(sql);
  46. }
  47. /* (non-Javadoc)
  48. * @see com.dadi.chr.dao.SimpleJdbcTemplateDao#update(java.lang.String,Object[])
  49. */
  50. public Integer update(String sql, Object... params) {
  51. if(params.length == 0)return getJdbcTemplate().update(sql);
  52. return getJdbcTemplate().update(sql,params);
  53. }
  54. public Long getCountBySql(String sql, Object...params) {
  55. return getJdbcTemplate().queryForLong(sql,params);
  56. }
  57. public void batchSaveOrUpdate(String sql,final List<Object[]> params) {
  58. getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() {
  59. public void setValues(PreparedStatement pstat, int i) throws SQLException {
  60. Object[] ps = params.get(i);
  61. for(int p = 0 ; p < ps.length ; p++){
  62. pstat.setObject(p + 1, ps[p]);
  63. }
  64. }
  65. public int getBatchSize() {
  66. return params.size();
  67. }
  68. });
  69. }
  70. @SuppressWarnings("unchecked")
  71. public Map<String,Object> executeStoreProc(final String sql,final Object[] paramValues,final int[] outParamTypes){
  72. Map<String,Object> retMap = (Map<String,Object>)this.getJdbcTemplate().execute(new CallableStatementCreator() {
  73. public CallableStatement createCallableStatement(final Connection arg0) throws SQLException {
  74. final CallableStatement cs = arg0.prepareCall(sql);
  75. return cs;
  76. }
  77. }, new CallableStatementCallback() {
  78. public Object doInCallableStatement(final CallableStatement cs) throws SQLException, DataAccessException {
  79. Map<String,Object> resultMap = new HashMap<String,Object>();
  80. final List<List<Map<String,Object>>> allRsLst = new ArrayList<List<Map<String,Object>>>();
  81. if(paramValues != null){
  82. for(int i = 0 ; i < paramValues.length ; i++){
  83. cs.setObject(i + 1, paramValues[i]);
  84. }
  85. }
  86. if(outParamTypes != null){
  87. for(int i = 0 ; i < outParamTypes.length ;i++){
  88. cs.registerOutParameter(paramValues.length + i + 1, outParamTypes[i]);
  89. }
  90. }
  91. cs.execute();
  92. ResultSet rs = cs.getResultSet();
  93. while (rs == null && cs.getMoreResults()) {
  94. rs = cs.getResultSet();
  95. }
  96. if(rs == null){
  97. rs = cs.executeQuery();
  98. }
  99. while (true) {
  100. if (rs != null) {
  101. List<Map<String,Object>> rsLst = new ArrayList<Map<String,Object>>();
  102. ResultSetMetaData rsmd = rs.getMetaData();
  103. int count = rsmd.getColumnCount();
  104. while (rs.next()) {
  105. Map map = new HashMap();
  106. for (int i = 1; i <= count; i++) {
  107. final String key = rsmd.getColumnLabel(i);
  108. final Object value = rs.getObject(key);
  109. map.put(key, value);
  110. }
  111. rsLst.add(map);
  112. }
  113. allRsLst.add(rsLst);
  114. }
  115. if (cs.getMoreResults()) {
  116. rs.close();
  117. rs = cs.getResultSet();
  118. } else {
  119. if(rs != null){
  120. rs.close();
  121. }
  122. break;
  123. }
  124. }
  125. resultMap.put("rs", allRsLst);
  126. if(outParamTypes != null){
  127. Map<Integer,Object> map = new HashMap<Integer,Object>();
  128. for(int i = 0 ; i < outParamTypes.length ;i++){
  129. Integer key = paramValues.length + i + 1;
  130. map.put(key,cs.getObject(key));
  131. }
  132. resultMap.put("out", map);
  133. }
  134. return resultMap;
  135. }
  136. });
  137. return retMap;
  138. }
  139. @Override
  140. public Integer updateGetKey(final String sql) throws Exception {
  141. KeyHolder keyHolder = new GeneratedKeyHolder();
  142. getJdbcTemplate().update(new PreparedStatementCreator() {
  143. @Override
  144. public PreparedStatement createPreparedStatement(Connection arg0)
  145. throws SQLException {
  146. PreparedStatement ps = arg0.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
  147. return ps;
  148. }
  149. }, keyHolder);
  150. return keyHolder.getKey().intValue();
  151. }
  152. @Override
  153. public void batchSaveOrUpdate(String[] sqls) {
  154. getJdbcTemplate().batchUpdate(sqls);
  155. }
  156. }


ReadExeclDataServiceImpl.class
  1. package com.dadi.oa.service.impl;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import org.apache.commons.logging.Log;
  7. import org.apache.commons.logging.LogFactory;
  8. import com.dadi.oa.dao.SimpleHibernateTempleDao;
  9. import com.dadi.oa.dao.SimpleJdbcTemplateDao;
  10. import com.dadi.oa.service.ReadExeclDataService;
  11. import com.dadi.oa.system.ConstantsUtil;
  12. import com.dadi.oa.util.ExeclReader;
  13. import com.sun.star.uno.RuntimeException;
  14. public class ReadExeclDataServiceImpl implements ReadExeclDataService{
  15. private Log logger = LogFactory.getLog(this.getClass());
  16. private SimpleJdbcTemplateDao jdbcDao;
  17. private SimpleHibernateTempleDao hbnDao;
  18. public void setJdbcDao(SimpleJdbcTemplateDao jdbcDao) {
  19. this.jdbcDao = jdbcDao;
  20. }
  21. public void setHbnDao(SimpleHibernateTempleDao hbnDao) {
  22. this.hbnDao = hbnDao;
  23. }
  24. @Override
  25. public void saveGatherDataMsg(ExeclReader reader,
  26. HashMap<String, String> inputMap) {
  27. //HashMap retMap = new HashMap();
  28. try {
  29. String title = inputMap.get("title");
  30. String userid = inputMap.get("userid");
  31. Integer dataMsgId = jdbcDao.
  32. updateGetKey("INSERT INTO dbo.t_dataPublish " +
  33. " ( creatorId , "+
  34. " createDate , "+
  35. " title , "+
  36. " remark , "+
  37. " publishstatus , "+
  38. " deleteflag "+
  39. " ) "+
  40. "VALUES ( "+userid+" , "+
  41. " GETDATE() , " +
  42. " '"+title+"' , "+
  43. " '' , "+
  44. " 0 , "+
  45. " 0 "+
  46. " )");
  47. List headerData = reader.getHeaderData();
  48. inputMap.put("dataMsgId", String.valueOf(dataMsgId));
  49. Integer[] datacolumnids = new Integer[headerData.size()];
  50. for (int i = 0 ; i < headerData.size() ; i++) {
  51. HashMap<String, String> cellMap = (HashMap<String, String>) headerData.get(i);
  52. Integer datacolumnid = jdbcDao
  53. .updateGetKey("INSERT dbo.t_dataPublishColumn "+
  54. " ( t_dataPublish_id , "+
  55. " columnName , " +
  56. " columnType "+
  57. " ) " +
  58. "VALUES (" +
  59. " "+dataMsgId+", "+
  60. " '"+cellMap.get("val")+"' , "+
  61. " "+ConstantsUtil.gatherDataColumnStatus.get("COMMON_COLUMN")+
  62. " )");
  63. cellMap.put("datacolumnid", String.valueOf(datacolumnid));
  64. datacolumnids[i] = datacolumnid;
  65. }
  66. ArrayList<String> datadetailsqls = new ArrayList<String>();
  67. for (int i = 1; i < reader.getDataMap().size(); i++) {
  68. ArrayList rowData = (ArrayList) reader.getDataMap().get(i);
  69. for (int j = 0; j < rowData.size(); j++) {
  70. HashMap<String, String> cellMap = (HashMap<String, String>) rowData.get(j);
  71. datadetailsqls.add("INSERT INTO dbo.t_dataPublishDetail "+
  72. " ( t_dataPublishColumn_id , "+
  73. " rownum , "+
  74. " cellValue "+
  75. " ) "+
  76. " VALUES ( "+datacolumnids[j]+" , "+
  77. " "+cellMap.get("rowNum")+" , "+
  78. " '"+cellMap.get("val")+"' "+
  79. " )");
  80. }
  81. }
  82. String[] batchsqls = new String[datadetailsqls.size()];
  83. jdbcDao.batchSaveOrUpdate(datadetailsqls.toArray(batchsqls));
  84. } catch (Exception e) {
  85. e.printStackTrace();
  86. logger.error("===========ERROR:ReadExeclDataServiceImpl.saveGatherDataMsg()");
  87. throw new RuntimeException("服务器异常!!!");
  88. }
  89. //retMap.put("resultStr", resultStr);
  90. }
  91. }


2.后面还想到一种方式,可以根据业务需求拼成一长串sql语句,包括定义变量,循环数据等,后面木有采用

05-11 22:05