PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/ etmvc stworthy/et-ar/src/com/et/ar/DaoSupport.java

http://etmvc.googlecode.com/
Java | 467 lines | 388 code | 46 blank | 33 comment | 91 complexity | 2add2d4ec295a8563b16fdf67c74c010 MD5 | raw file
Possible License(s): LGPL-3.0
  1. package com.et.ar;
  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.ResultSetMetaData;
  6. import java.sql.SQLException;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11. import org.apache.commons.logging.Log;
  12. import org.apache.commons.logging.LogFactory;
  13. import com.et.ar.adapters.Adapter;
  14. import com.et.ar.annotations.GeneratorType;
  15. import com.et.ar.exception.DataAccessException;
  16. import com.et.ar.exception.FieldAccessException;
  17. import com.et.ar.orm.ColumnField;
  18. public class DaoSupport {
  19. private static Log log = LogFactory.getLog("ActiveRecord");
  20. private Connection conn;
  21. public DaoSupport(Connection conn){
  22. this.conn = conn;
  23. }
  24. public <E> int insert(E obj, Adapter adapter) throws FieldAccessException,DataAccessException {
  25. Class<?> c = obj.getClass();
  26. OrmInfo orm = OrmInfo.getOrmInfo(c);
  27. if (adapter != null && orm.idGeneratorType == GeneratorType.AUTO){
  28. String adapterName = adapter.getAdapterName();
  29. if (adapterName.equals("mysql")){
  30. orm.idGeneratorType = GeneratorType.AUTO;
  31. }
  32. else if (adapterName.equals("oracle")){
  33. orm.idGeneratorType = GeneratorType.SEQUENCE;
  34. }
  35. else if (adapterName.equals("sqlserver")){
  36. orm.idGeneratorType = GeneratorType.IDENTITY;
  37. }
  38. else if (adapterName.equals("db2")){
  39. orm.idGeneratorType = GeneratorType.IDENTITY;
  40. }
  41. }
  42. if (orm.idGeneratorType == GeneratorType.AUTO ||
  43. orm.idGeneratorType == GeneratorType.IDENTITY ||
  44. orm.idGeneratorType == GeneratorType.SEQUENCE){
  45. String sql1 = "insert into "+orm.table+"(";
  46. String sql2 = "values(";
  47. if (orm.idGeneratorType == GeneratorType.SEQUENCE){
  48. if (adapter != null){
  49. String sequenceName = orm.table+"_seq"; //????
  50. Object nextval = executeScalar(adapter.getSequenceNextValString(sequenceName), null);
  51. nextval = ConvertUtil.castFromObject(nextval, orm.idType);
  52. sql1 += orm.id + ",";
  53. sql2 += nextval.toString() + ",";
  54. OrmInfo.setFieldValue(c, orm.id, obj, nextval); //????????
  55. }
  56. else{
  57. String selectMaxSql = "select max(" + orm.id + ") from " + orm.table;
  58. Object maxId = executeScalar(selectMaxSql, null);
  59. Long nextId = Long.parseLong(maxId.toString()) + 1;
  60. Object nextval = ConvertUtil.castFromObject(nextId.toString(), orm.idType);
  61. sql1 += orm.id + ",";
  62. sql2 += nextval.toString() + ",";
  63. OrmInfo.setFieldValue(c, orm.id, obj, nextval);
  64. }
  65. }
  66. Object[] args = new Object[orm.columnFields.length];
  67. for(int i=0; i<orm.columnFields.length; i++){
  68. ColumnField field = orm.columnFields[i];
  69. sql1 += field.getName() + ",";
  70. sql2 += "?,";
  71. args[i] = OrmInfo.getFieldValue(c, field.getName(), obj);
  72. }
  73. String sql = sql1.substring(0,sql1.length()-1)+") " + sql2.substring(0,sql2.length()-1)+")";
  74. int updated = execute(sql, args);
  75. //??????
  76. if (orm.idGeneratorType != GeneratorType.SEQUENCE){
  77. if (adapter != null){
  78. Object id = executeScalar(adapter.getIdentitySelectString(), null);
  79. id = ConvertUtil.castFromObject(id.toString(), orm.idType);
  80. OrmInfo.setFieldValue(c, orm.id, obj, id);
  81. }
  82. else{
  83. String selectMaxSql = "select max(" + orm.id + ") from " + orm.table;
  84. Object maxId = executeScalar(selectMaxSql, null);
  85. maxId = ConvertUtil.castFromObject(maxId, orm.idType);
  86. OrmInfo.setFieldValue(c, orm.id, obj, maxId);
  87. }
  88. }
  89. OrmInfo.setFieldValue(ActiveRecordBase.class, "isnewrecord", obj, false);
  90. return updated;
  91. }
  92. else{
  93. String sql1 = "insert into " + orm.table + "(";
  94. String sql2 = "values(";
  95. List<Object> tmpArgs = new ArrayList<Object>();
  96. if (orm.id != null){
  97. sql1 += orm.id + ",";
  98. sql2 += "?,";
  99. Object value = OrmInfo.getFieldValue(c, orm.id, obj);
  100. tmpArgs.add(value);
  101. }
  102. for(ColumnField field: orm.columnFields){
  103. sql1 += field.getName() + ",";
  104. sql2 += "?,";
  105. Object value = OrmInfo.getFieldValue(c, field.getName(), obj);
  106. tmpArgs.add(value);
  107. }
  108. String sql = sql1.substring(0,sql1.length()-1)+") " + sql2.substring(0,sql2.length()-1)+")";
  109. Object[] args = tmpArgs.toArray();
  110. int updated = execute(sql, args);
  111. OrmInfo.setFieldValue(ActiveRecordBase.class, "isnewrecord", obj, false);
  112. return updated;
  113. }
  114. }
  115. public int updateAll(Class<?> c, String updates, Object[] update_args, String conditions, Object[] condition_args) throws DataAccessException{
  116. OrmInfo orm = OrmInfo.getOrmInfo(c);
  117. List<Object> tmpArgs = new ArrayList<Object>();
  118. String sql = "update " + orm.table + " set " + updates;
  119. if (update_args != null){
  120. for(Object arg: update_args){
  121. tmpArgs.add(arg);
  122. }
  123. }
  124. if (conditions != null && !conditions.equals("")){
  125. sql += " where " + conditions;
  126. if (condition_args != null){
  127. for(Object arg: condition_args){
  128. tmpArgs.add(arg);
  129. }
  130. }
  131. }
  132. Object[] args = tmpArgs.toArray();
  133. return execute(sql, args);
  134. }
  135. public <E> int update(E obj) throws FieldAccessException,DataAccessException{
  136. Class<?> clasz = obj.getClass();
  137. if (((ActiveRecordBase)obj).isProxy()){
  138. clasz = clasz.getSuperclass();
  139. }
  140. OrmInfo orm = OrmInfo.getOrmInfo(clasz);
  141. Object[] args = new Object[orm.columnFields.length+1];
  142. String sql = "update " + orm.table + " set ";
  143. for (int i=0; i<orm.columnFields.length; i++){
  144. ColumnField field = orm.columnFields[i];
  145. sql += field.getName() + "=?,";
  146. args[i] = OrmInfo.getFieldValue(clasz, field.getName(), obj);
  147. }
  148. sql = sql.substring(0, sql.length()-1) + " where " + orm.id + "=?";
  149. args[orm.columnFields.length] = OrmInfo.getFieldValue(clasz, orm.id, obj);
  150. int updated = execute(sql, args);
  151. OrmInfo.setFieldValue(ActiveRecordBase.class, "isnewrecord", obj, false);
  152. return updated;
  153. }
  154. public int deleteAll(Class<?> clasz, String conditions, Object[] args) throws DataAccessException{
  155. OrmInfo orm = OrmInfo.getOrmInfo(clasz);
  156. String sql = "delete from " + orm.table;
  157. if (conditions != null && !conditions.equals("")){
  158. sql += " where " + conditions;
  159. }
  160. return execute(sql, args);
  161. }
  162. public <E> int delete(E obj) throws FieldAccessException,DataAccessException{
  163. Class<?> clasz = obj.getClass();
  164. if (((ActiveRecordBase)obj).isProxy()){
  165. clasz = clasz.getSuperclass();
  166. }
  167. OrmInfo orm = OrmInfo.getOrmInfo(clasz);
  168. Object id = OrmInfo.getFieldValue(clasz, orm.id, obj);
  169. String sql = "delete from " + orm.table + " where " + orm.id + "=?";
  170. Object[] args = new Object[]{id};
  171. return execute(sql, args);
  172. }
  173. public List<Map<String,Object>> select(String sql, Object[] args, int limit, int offset) throws DataAccessException{
  174. List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
  175. PreparedStatement pstmt = null;
  176. ResultSet rs = null;
  177. Object[] sqlParts = buildSql(sql, args);
  178. sql = sqlParts[0].toString();
  179. args = (Object[])sqlParts[1];
  180. String sqlInfo = sqlParts[2].toString();
  181. try{
  182. long t1 = System.currentTimeMillis();
  183. pstmt = conn.prepareStatement(sql);
  184. if (args != null){
  185. for(int i=0; i<args.length; i++){
  186. pstmt.setObject(i+1, args[i]);
  187. }
  188. }
  189. if (limit > 0){
  190. //????????????????????
  191. try{
  192. pstmt.setMaxRows(limit+offset);
  193. }
  194. catch(Exception e){}
  195. }
  196. rs = pstmt.executeQuery();
  197. int count = 0;
  198. while(count < offset && rs.next()){
  199. count ++;
  200. }
  201. ResultSetMetaData meta = rs.getMetaData();
  202. count = 0;
  203. while(rs.next() && (limit == 0 || count++ < limit)){
  204. Map<String,Object> item = new HashMap<String,Object>();
  205. for(int i=1; i<=meta.getColumnCount(); i++){
  206. String name = meta.getColumnName(i).toLowerCase();
  207. Object value = rs.getObject(i);
  208. item.put(name, value);
  209. }
  210. data.add(item);
  211. }
  212. long t2 = System.currentTimeMillis();
  213. if (log.isDebugEnabled()){
  214. log.debug((t2-t1)/1000.0 + "s " + sqlInfo);
  215. }
  216. }
  217. catch(SQLException e1){
  218. throw new DataAccessException(sqlInfo, e1);
  219. }
  220. finally{
  221. try{
  222. if (rs != null){
  223. rs.close();
  224. }
  225. if (pstmt != null){
  226. pstmt.close();
  227. }
  228. }
  229. catch(SQLException e){
  230. throw new DataAccessException(e);
  231. }
  232. }
  233. return data;
  234. }
  235. public <E> List<E> select(Class<E> clasz, String sql, Object[] args, int limit, int offset) throws FieldAccessException,DataAccessException{
  236. OrmInfo orm = OrmInfo.getOrmInfo(clasz);
  237. boolean useProxy = true;
  238. if (orm.hasManyFields.length==0 && orm.belongsToFields.length==0 && orm.hasOneFields.length==0){
  239. useProxy = false; //????????
  240. }
  241. List<E> data = new ArrayList<E>();
  242. List<Map<String,Object>> items = select(sql, args, limit, offset);
  243. for(Map<String,Object> item: items){
  244. E obj;
  245. if (useProxy == false){
  246. try{
  247. obj = clasz.newInstance();
  248. }
  249. catch(Exception ex){
  250. throw new FieldAccessException(ex);
  251. }
  252. }
  253. else{
  254. ActiveRecordProxy proxy = new ActiveRecordProxy();
  255. obj = proxy.getProxyObject(clasz);
  256. if (obj instanceof ActiveRecordBase) {
  257. OrmInfo.setFieldValue(ActiveRecordBase.class, "isproxy", obj, true);
  258. }
  259. }
  260. if (obj instanceof ActiveRecordBase) {
  261. OrmInfo.setFieldValue(ActiveRecordBase.class, "isnewrecord", obj, false);
  262. }
  263. if (orm.id != null){
  264. Object value = item.get(orm.id.toLowerCase());
  265. value = ConvertUtil.castFromObject(value, orm.idType);
  266. OrmInfo.setFieldValue(clasz, orm.id, obj, value);
  267. }
  268. for(ColumnField field: orm.columnFields){
  269. Object value = item.get(field.getName().toLowerCase());
  270. value = ConvertUtil.castFromObject(value, field.getType());
  271. OrmInfo.setFieldValue(clasz, field.getName(), obj, value);
  272. }
  273. data.add(obj);
  274. }
  275. return data;
  276. }
  277. public int execute(String sql, Object[] args) throws DataAccessException{
  278. int updated = 0;
  279. Object[] sqlParts = buildSql(sql, args);
  280. sql = sqlParts[0].toString();
  281. args = (Object[])sqlParts[1];
  282. String sqlInfo = sqlParts[2].toString();
  283. PreparedStatement pstmt = null;
  284. try{
  285. long t1 = System.currentTimeMillis();
  286. pstmt = this.conn.prepareStatement(sql);
  287. if (args != null){
  288. for(int i=0; i<args.length; i++){
  289. pstmt.setObject(i+1, args[i]);
  290. }
  291. }
  292. updated = pstmt.executeUpdate();
  293. long t2 = System.currentTimeMillis();
  294. if (log.isDebugEnabled()){
  295. log.debug((t2-t1)/1000.0 + "s " + sqlInfo);
  296. }
  297. }
  298. catch(SQLException e){
  299. throw new DataAccessException(sqlInfo, e);
  300. }
  301. finally{
  302. try{
  303. if (pstmt != null){
  304. pstmt.close();
  305. }
  306. }
  307. catch(SQLException e){
  308. throw new DataAccessException(e);
  309. }
  310. }
  311. return updated;
  312. }
  313. public Object executeScalar(String sql, Object[] args) throws DataAccessException{
  314. PreparedStatement pstmt = null;
  315. ResultSet rs = null;
  316. Object scalar = null;
  317. Object[] sqlParts = buildSql(sql, args);
  318. sql = sqlParts[0].toString();
  319. args = (Object[])sqlParts[1];
  320. String sqlInfo = sqlParts[2].toString();
  321. try{
  322. long t1 = System.currentTimeMillis();
  323. pstmt = this.conn.prepareStatement(sql);
  324. if (args != null){
  325. for(int i=0; i<args.length; i++){
  326. pstmt.setObject(i+1, args[i]);
  327. }
  328. }
  329. rs = pstmt.executeQuery();
  330. if (rs.next()){
  331. scalar = rs.getObject(1);
  332. }
  333. long t2 = System.currentTimeMillis();
  334. if (log.isDebugEnabled()){
  335. log.debug((t2-t1)/1000.0 + "s " + sqlInfo);
  336. }
  337. }
  338. catch(SQLException e){
  339. throw new DataAccessException(sqlInfo, e);
  340. }
  341. finally{
  342. try{
  343. if (rs != null){
  344. rs.close();
  345. }
  346. if (pstmt != null){
  347. pstmt.close();
  348. }
  349. }
  350. catch(SQLException e){
  351. throw new DataAccessException(e);
  352. }
  353. }
  354. return scalar;
  355. }
  356. /**
  357. * ??SQL??????NULL???
  358. * @param sql ??SQL??
  359. * @param args ????
  360. * @return ??????????SQL?????????SQL??
  361. */
  362. private Object[] buildSql(String sql, Object[] args){
  363. Object[] result = new Object[3];
  364. if (args == null){
  365. result[0] = sql;
  366. result[1] = args;
  367. result[2] = sql;
  368. return result;
  369. }
  370. String newSql = "";
  371. String showSql = "";
  372. List<Object> tmpArgs = new ArrayList<Object>();
  373. String[] ss = (sql + " ").split("\\?");
  374. for(int i=0; i<ss.length-1; i++){
  375. Object arg = args[i];
  376. if (arg == null) {
  377. newSql += ss[i] + "null";
  378. showSql += ss[i] + "null";
  379. } else {
  380. newSql += ss[i] + "?";
  381. tmpArgs.add(arg);
  382. if (arg instanceof String) {
  383. showSql += ss[i] + "'" + arg + "'";
  384. } else {
  385. showSql += ss[i] + arg.toString();
  386. }
  387. }
  388. }
  389. newSql += ss[ss.length - 1];
  390. showSql += ss[ss.length - 1];
  391. result[0] = newSql;
  392. result[1] = tmpArgs.toArray();
  393. result[2] = showSql;
  394. return result;
  395. }
  396. /*
  397. private String buildSql1(String sql, Object[] args){
  398. if (args == null){
  399. return sql;
  400. }
  401. String[] ss = (sql + " ").split("\\?");
  402. sql = "";
  403. for(int i=0; i<ss.length-1; i++){
  404. Object arg = args[i];
  405. String val = "";
  406. if (arg == null){
  407. val = "null";
  408. } else if (arg instanceof String){
  409. val = "'" + arg + "'";
  410. } else {
  411. val = arg.toString();
  412. }
  413. sql += ss[i] + val;
  414. }
  415. sql += ss[ss.length-1];
  416. return sql;
  417. }
  418. */
  419. }