📄 customizedoperation.java
字号:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package ActiveObject.core;import ActiveObject.exception.*;import ActiveObject.vo.IntermediaryExpression;import java.sql.*;import java.util.*;/** * @author tanjiazhang */public abstract class CustomizedOperation {// protected Class[] objectTypes = null;// protected String condition = null;// protected String setting = null;// protected Object[] params = null;// protected Map<String, Order> orders = null;// protected Map<String, String> aliasMap = new HashMap<String, String>(); protected IntermediaryExpression expression = new IntermediaryExpression(); abstract protected String toSQLString() throws ObjectAnalysisException; public CustomizedOperation(Object... objects) throws ArgumentFormatError { Map<String, String> aliasMap = new HashMap<String, String>(); Class[] objectTypes = null; int length = objects.length-1; List<Class> tempObjectTypes = new LinkedList<Class>();//初步估计用户关联表的数量的平均值<=2 for(int i=0;i<=length;i++) { Object item = objects[i]; if(item instanceof Class) { if(tempObjectTypes.contains((Class)item))//如果发现重复的类型 { throw new ArgumentFormatError("Except a different Object Type from others at the position of "+String.valueOf(i+1)); } tempObjectTypes.add((Class)item); if(i<length && objects[i+1] instanceof String)//这是用户自定义了别名的情况 { aliasMap.put(((Class)item).getSimpleName(), (String)objects[i+1]); i++;//跳过下一个单元,因为它是别名,并且已经加入map了 } else//这是用户没有自定义别名的情况,系统自动引用每个类的第一个字母作别名。如有重复,则设为首字母加编号,如user,univer->u1, u2 { String simpleName = ((Class)item).getSimpleName(); int nameIndex = 1; String prifix = simpleName.substring(0, 1); String tempName = prifix; while(aliasMap.containsValue(tempName)) { nameIndex++; prifix += String.valueOf(nameIndex); } aliasMap.put(simpleName, tempName);//将别名放入映射里 if(nameIndex == 2)//如果等于2,说明之前的tempName未加上1后缀 { //寻找前面的tempName并在它尾部加上1 String shortName = simpleName.substring(0, 1); for(String key : aliasMap.keySet()) { if(aliasMap.get(key).equals(shortName)) { aliasMap.put(key, shortName+String.valueOf(1)); break; } } } } } else if(item instanceof String)//如无意外不会到达这个分支,除非用户参数错误 { throw new ArgumentFormatError("Expect an argument of class type at the position of "+String.valueOf(i+1)); } } //构造返回类型 objectTypes = new Class[tempObjectTypes.size()]; tempObjectTypes.toArray(objectTypes); expression.setAliasMap(aliasMap); expression.setObjectTypes(objectTypes); } public CustomizedOperation(Object[] objects, String condition, Object... params) throws ArgumentFormatError { this(objects, null, condition, params); } public CustomizedOperation(Object[] objects, String setting, String condition, Object... params) throws ArgumentFormatError {//System.err.println("haha"); //构造别名映射aliasMap和复制参数 Map<String, String> aliasMap = new HashMap<String, String>(); Class[] objectTypes = null; Object[] paramValues = null; int length = objects.length-1; List<Class> tempObjectTypes = new LinkedList<Class>();//初步估计用户关联表的数量的平均值<=2 for(int i=0;i<=length;i++) { Object item = objects[i]; if(item instanceof Class) { if(tempObjectTypes.contains((Class)item))//如果发现重复的类型 { throw new ArgumentFormatError("Except a different Object Type from others at the position of "+String.valueOf(i+1)); } tempObjectTypes.add((Class)item); if(i<length && objects[i+1] instanceof String)//这是用户自定义了别名的情况 { aliasMap.put(((Class)item).getSimpleName(), (String)objects[i+1]); i++;//跳过下一个单元,因为它是别名,并且已经加入map了 } else//这是用户没有自定义别名的情况,系统自动引用每个类的第一个字母作别名。如有重复,则设为首字母加编号,如user,univer->u1, u2 { String simpleName = ((Class)item).getSimpleName(); int nameIndex = 1; String prifix = simpleName.substring(0, 1); String tempName = prifix; while(aliasMap.containsValue(tempName)) { nameIndex++; prifix += String.valueOf(nameIndex); } aliasMap.put(simpleName, tempName);//将别名放入映射里 if(nameIndex == 2)//如果等于2,说明之前的tempName未加上1后缀 { //寻找前面的tempName并在它尾部加上1 String shortName = simpleName.substring(0, 1); for(String key : aliasMap.keySet()) { if(aliasMap.get(key).equals(shortName)) { aliasMap.put(key, shortName+String.valueOf(1)); break; } } } } } else if(item instanceof String)//如无意外不会到达这个分支,除非用户参数错误 { throw new ArgumentFormatError("Expect an argument of class type at the position of "+String.valueOf(i+1)); } } //构造返回类型 objectTypes = new Class[tempObjectTypes.size()]; tempObjectTypes.toArray(objectTypes); //复制参数 //System.err.println(setting+" - "+OQLParser.getPlaceSymbolCount(condition)+" "+OQLParser.getPlaceSymbolCount(setting)); paramValues = new Object[OQLParser.getPlaceSymbolCount(condition)+OQLParser.getPlaceSymbolCount(setting)]; for(int i=0;i<params.length;i++) { paramValues[i] = params[i]; } //替换条件语句的完整类名 this.expression.setCondition(OQLParser.replaceWithAlias(condition, aliasMap)); if(setting != null) this.expression.setSetting(OQLParser.replaceWithAlias(setting, aliasMap)); expression.setAliasMap(aliasMap); expression.setCondition(condition); expression.setObjectTypes(objectTypes); //expression.setOrders(orders); expression.setParamValues(paramValues); } public void addCondition(String condition) { //替换条件语句的完整类名 this.expression.setCondition(OQLParser.replaceWithAlias(condition, this.expression.getAliasMap())); } public void addSetting(String setting) { //替换条件语句的完整类名 this.expression.setCondition(OQLParser.replaceWithAlias(setting, this.expression.getAliasMap())); } public static void main(String... args) throws Exception {// CustomizedOperation sql = new CustomizedOperation(new Object[]{User.class,"xx", Role.class}, "???", 1,1,3) {//// @Override// protected String toSQLString() {// throw new UnsupportedOperationException("Not supported yet.");// }// };// for(String item : sql.aliasMap.keySet())// {// System.out.println(item +": " + sql.aliasMap.get(item));// }// for(Class item : sql.objectTypes)// {// System.out.println(item.getSimpleName());// } } protected final int excuteUpdate() throws SQLException, ObjectAnalysisException//this.toSQLString(), this.expression.getParamValues() { return ActiveRecordHelper.excuteUpdate(this.toSQLString(), this.expression.getParamValues()); } protected List excuteQuery() throws SQLException, ObjectAnalysisException { Connection connection = ActiveRecord.getConnection(); PreparedStatement stmt = connection.prepareStatement(toSQLString()); int index = 1; for (Object item : this.expression.getParamValues()) { stmt.setObject(index++, item); } ResultSet rs = stmt.executeQuery(); List list = new ArrayList(); Class[] objectTypes = this.expression.getObjectTypes(); Map<String, String> aliasMap = this.expression.getAliasMap(); int tableCount = objectTypes.length; if (tableCount > 1) { while (rs.next()) { ActiveRecord[] objects = new ActiveRecord[tableCount]; for (int j = 0; j < tableCount; j++) { try { objects[j] = (ActiveRecord) objectTypes[j].newInstance(); } catch (Exception err) { throw new ObjectAnalysisException(err); } } list.add(ActiveRecordHelper.setupObjectByResultSet(objects, rs, aliasMap)); } } else { while (rs.next()) { try { list.add(ActiveRecordHelper.setupObjectByResultSet((ActiveRecord)objectTypes[0].newInstance(), rs)); } catch (SQLException err) { throw err; } catch (Exception err) { throw new ObjectAnalysisException(err); } } } return list; } /** * 返回表别名部分语句,包含前后空格。例如 user as u,role as r * @return */// protected String createAliasStatement() throws ObjectAnalysisException// {// StringBuffer sql = new StringBuffer(50);// int objectIndex = objectTypes.length-1;// for(int index=0;index<=objectIndex;index++)// {// ObjectInfo recordType = recordType = ActiveRecordHelper.analizeObjectInfo(objectTypes[index]);// sql.append(recordType.getTableName());// sql.append(" as ");// sql.append(this.aliasMap.get(objectTypes[index].getSimpleName()));// if(index == objectIndex)// {// if(!OQLParser.isContentEmpty(condition))// sql.append(" ");// }// else// sql.append(",");// }// return sql.toString();// } /** * 返回排序部分语句,包含前后空格。例如 order by u.id DESC, u.name ASC * @return 如果没有添加排序条件则返回空 */// protected String createOrderStatement()// {// if(this.orders == null)// return null;// int index = 1;// StringBuffer expandCondition = new StringBuffer(50);// //添加排序控制// expandCondition.append(" order by ");// int size = this.orders.size();// for(String key : this.orders.keySet())// {// expandCondition.append(key);// if(this.orders.get(key) == Order.DESC)// expandCondition.append(" DESC ");// else// expandCondition.append(" ASC ");// if(index == size)// expandCondition.append(' ');// else// expandCondition.append(",");// index++;// }// return expandCondition.toString();// } public CustomizedOperation setParameter(int index, Object value) { this.expression.getParamValues()[index] = value; return this; } /** * 添加排序条件 * @param field * @param sortOrder * @return */ protected final void addOrderUtil (String field, Order sortOrder) { if(this.expression.getOrders() == null) this.expression.setOrders(new HashMap<String, Order>()); this.expression.getOrders().put(field, sortOrder); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -