⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 genericfactorygenerator.java

📁 OR Mapping工具
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
package org.ephman.abra.tools;import org.ephman.utils.*;import java.io.*;import java.util.*;/**  (this is the generic base a db specific descendant will be copied into this package * given a base output directory * generate a factory class for get/put when given a JClass descriptor * @author Paul M. Bethe * @version 0.0.2 */public abstract class GenericFactoryGenerator implements AbraTypes {	private String outdir;	private char fileSeperator;	private String defaultExtend;	private boolean useProcs;	//	private boolean isPostgres;	/** make a new generator with a base directory of outdir	 * so for foo.bar.FooBar if outdir = /home/dknull	 * and file_sep = '/' then a class /home/dknull/foo/bar/AbstractFooBarFactory.java is created	 * @param outdir the base directory for writing files	 * @param file_sep the file seperator ('/' for unix/linux , '\\' for Windows)	 */	public GenericFactoryGenerator (String outdir, char file_sep, String imp, boolean useProcs) {		this.outdir = outdir;		this.fileSeperator = file_sep;		this.defaultExtend = imp;		this.useProcs = useProcs;			}	String END_DATE = "end_date";	String constructorString = "";	public void generate (JClass currentClass) throws IOException, SchemaException {		String fname = currentClass.getPackageName().replace('.', fileSeperator) + fileSeperator +"Abstract"              + currentClass.getClassName() + "Factory.java";        FileWriter outFile = new FileWriter (outdir + fileSeperator + fname);		Debugger.trace ("Generating factory " + outdir + fileSeperator + fname, Debugger.VERBOSE);		constructorString = "";        writeFactoryHeader (outFile, currentClass);		Vector allFields = new Vector(currentClass.getAllFields ().values());		writeFactoryMethods (outFile, currentClass, allFields);		writeFactoryLinks (outFile, currentClass, allFields);        writeFactoryTrailer (outFile, currentClass);        outFile.close ();	}	private void writeFactoryLinks (FileWriter outFile, JClass currentClass, Vector allFields) throws IOException, SchemaException {		outFile.write ("\tpublic String getPrimaryColumn () { ");		outFile.write ("return \"" + currentClass.getPrimaryKey() + "\"; }\n");		outFile.write ("\n\tpublic String getTableName () { ");		outFile.write ("return tableName; }\n");		outFile.write ("\n\n\t// the variables to map Java to Sql\n\n");		outFile.write ("\tprotected final String tableName = \"" + currentClass.getTableName () + "\";\n\n");		for (int i = 0; i < allFields.size (); i++) {			JField jf = (JField)allFields.elementAt (i);			String name = jf instanceof JCompositeField ? jf.getJavaName () + "Oid" : jf.getJavaName ();			if (jf.isInline ()) {				JCompositeField jcf = (JCompositeField)jf;				InlineFieldWriter iw = new InlineFieldWriter (jcf, currentClass){						public void writeOneField (FileWriter outFile, JField subField,												   String sqlName, String preName,												   boolean isFirst) 							throws IOException, SchemaException {							String v_name = preName + subField.getJavaName ();							outFile.write ("\tpublic final String " + v_name + " = \"" 										   + prefix										   + subField.getSqlName () + "\";\n\n");						}					};				iw.execute (outFile, false);				/* factored 				   JClass fieldClass = jcf.getJClass ();				   Vector fields = new Vector (fieldClass.getAllFields ().values ());				   String subPrimaryKey = fieldClass.getPrimaryKey ();				   String prefix = jcf.getPrefix () + "_";				   for (int j = 0; j < fields.size (); j++) {				   JField subField = (JField)fields.elementAt (j);				   String sqlName = subField.getSqlName ();				   String preName = jf.getJavaName () + "_";				   				   if (sqlName.equals (subPrimaryKey)) {				   // do nothing ..				   }				   else if (subField instanceof JCompositeField) {				   throw new SchemaException ("ephman.abra.tools.nocompinline", 				   currentClass.getSchemaFileName ()); 				   }				   else {				   name = preName + subField.getJavaName ();				   outFile.write ("\tpublic final String " + name + " = \"" + prefix				   + subField.getSqlName () + "\";\n\n");				   }				   } */			}			else if (jf.isDbColumn ())				outFile.write ("\tpublic final String " + name + " = \"" + jf.getSqlName () + "\";\n\n");		}        if (currentClass.isVersioned())		    outFile.write ("\tpublic final String " + VERSION_NUMBER + " = \"" + VERSION_NUMBER + "\";\n\n");	}	// fac methods down here	private void writeUpdateMethod (FileWriter factoryOutFile, JClass currentClass, Vector allFields) throws IOException, SchemaException {		factoryOutFile.write ("\n/** this method returns the update string for the db */\n\n");		factoryOutFile.write ("\tprotected String makeUpdateString () {\n");		factoryOutFile.write ("\t\treturn updateString;\n\t}\n");		factoryOutFile.write ("\tprotected static final String updateString = ");		factoryOutFile.write ("\"update " + currentClass.getTableName () + " set \" +\n\t\t");		final String outChar = "?";		String prim_str = "";		boolean isFirst = true;		if (currentClass.isVersioned ()) {			isFirst = false;			factoryOutFile.write ("\"" + VERSION_NUMBER + " = " + outChar);		}		for (int i = 0; i < allFields.size(); i++) {			JField jf = (JField)allFields.elementAt (i);			if (jf.isDbColumn () && !isClob (jf) && !jf.isInline ()) {				String sqlName = jf.getSqlName ();				/*	if (jf instanceof JCompositeField) {					sqlName = ((JCompositeField)jf).getJClass ().getPrimaryKey ();					}*/				if (jf.getSqlName ().equals (currentClass.getPrimaryKey ())) {					prim_str = " where " + jf.getSqlName () + " = ?"; // is primary key				}				else {					if (!isFirst)						factoryOutFile.write (",\" +\n\t\t\"" + sqlName + " = " + outChar);					else {						isFirst = false;						factoryOutFile.write ("\"" + sqlName + " = " + outChar);					}				}			} else if (jf.isInline ()) {				JCompositeField jcf = (JCompositeField)jf;				InlineFieldWriter iw = new InlineFieldWriter (jcf, currentClass) {						public void writeOneField (FileWriter outFile, JField subField,												   String sqlName, String preName, 												   boolean isFirst) 							throws IOException, SchemaException {							if (!isFirst)								outFile.write (",\" +\n\t\t");														outFile.write ("\"" + prefix + 												  sqlName + " = " + outChar);						}					};				iw.execute (factoryOutFile, isFirst);				isFirst = false; // at least one inline - field				/* no more				   JClass fieldClass = jcf.getJClass ();				   Vector fields = new Vector (fieldClass.getAllFields ().values ());				   String subPrimaryKey = fieldClass.getPrimaryKey ();				   String prefix = jcf.getPrefix ();				   for (int j = 0; j < fields.size (); j++) {				   JField subField = (JField)fields.elementAt (j);				   String sqlName = subField.getSqlName ();				   				   if (!subField.isDbColumn() || sqlName.equals (subPrimaryKey)) {				   // do nothing ..				   }				   else if (subField instanceof JCompositeField) {				   throw new SchemaException ("ephman.abra.tools.nocompinline", 				   currentClass.getSchemaFileName ()); 				   }				   else {				   				   }										   } */			} else if (jf instanceof JCompositeField) {				JCompositeField jcf = ((JCompositeField)jf);				if (!(jcf.isCollection () || jcf.isTransient ()) && jcf.getJClass () == null) {					if (jcf.getSqlName().length() > 0 && !jcf.getSqlName().equals (jcf.getJavaName ())) {						// sql node found on composite (but no foreign table descriptor )						createErrorMsg (currentClass, jcf, "ephman.abra.tools.noforeign");					}					// else ok no sql node				}			}		}		if (prim_str.equals (""))			Debugger.trace ("!! No primary key found for class " + currentClass.getClassName (), Debugger.ERROR);		factoryOutFile.write (prim_str + "\";\n"); 	}	private void createErrorMsg (JClass currentClass, JField jf, String msg) throws SchemaException {				throw new SchemaException (currentClass, jf, msg);	}	private String findSetType (JField field) {		if (field.getDkType ().isComposite ())			return null; // is a com.foo.bar		String typeName =  field.getDkType ().getObjectTypeName ();		if (nativeClassSet.contains (typeName)) // is Integer, .. etc			return "Object";		return typeName.substring (0,1).toUpperCase () + typeName.substring (1);	}	private boolean isClob (JField jf) {		return jf.getSqlType ().equals ("clob");	}    private boolean hasClobs (Vector allFields) {        boolean result = false;        for (int i = 0; !result && (i < allFields.size()); i++) {            JField jf = (JField)allFields.get(i);            result = isClob (jf);        }        return result;    }	private void writeClobMethods (FileWriter factoryOutFile, JClass currentClass, Vector clobList)		throws IOException, SchemaException {		boolean hasClobs = false;		if (Checks.hasElements (clobList)) {			hasClobs = true;			// write setClobs method for each field in list..			factoryOutFile.write ("\n/** this method updates clobs to the db */\n");			factoryOutFile.write ("\tprotected void setClobs (DatabaseSession dbSess, ResultSet rs, Identified item) throws SQLException {\n");			factoryOutFile.write ("\t\t" + currentClass.getClassName () + " foo = (" + 								  currentClass.getClassName () + ")item;\n\n");			for (int i=0; i< clobList.size (); i++) {				JField jf  = (JField)clobList.elementAt (i);				factoryOutFile.write ("\t\tsuper.setClob (dbSess, rs, " + jf.getJavaName () + ", foo.get"									  + jf.getGetSet () + " ());\n");			}			factoryOutFile.write ("\t}\n\n");		}        writeHasClobsMethod(factoryOutFile, hasClobs);    }    private void writeHasClobsMethod(FileWriter factoryOutFile, boolean hasClobs) throws IOException {        factoryOutFile.write ("\n/** this method tells FactoryBase whether or not clobs exist */\n");        factoryOutFile.write ("\tprotected boolean hasClobs () { return " + hasClobs + "; }\n");    }    private void writeSetArgMethod (FileWriter factoryOutFile, JClass currentClass, Vector allFields, int key_loc)		throws IOException, SchemaException {		Vector clobList = new Vector ();		factoryOutFile.write ("\n/** this method sets the args for a prepared statement */\n\n");		factoryOutFile.write ("\tprotected void setArguments (PreparedStatement stmt, Object"							  + " obj, boolean update) throws SQLException {\n");		String varName =currentClass.getClassName ().substring (0,1).toLowerCase ()+currentClass.getClassName ().substring (1);		factoryOutFile.write ("\t\t" + currentClass.getClassName () + " " + varName + " = (" + currentClass.getClassName ()							  + ")obj;\n");		factoryOutFile.write ("\t\tint i = 1;\n");		factoryOutFile.write ("\t\tif (!update && useStoredProcs ()) // set return val..\n");		factoryOutFile.write ("\t\t\t((CallableStatement)stmt).registerOutParameter (i++, Types.INTEGER);\n");		if (currentClass.isVersioned ())			factoryOutFile.write ("\t\tstmt.setInt (i++, " + varName + ".getVersion ());\n");		String prim_str = "";		for (int i = 0; i < allFields.size (); i++) {			JField jf = (JField)allFields.elementAt (i);			if (jf.isDbColumn ()) {				if (isClob (jf))					clobList.addElement (jf);				else if (jf.isInline ()) {					JCompositeField jcf = (JCompositeField)jf;					InlineFieldWriter iw = new InlineFieldWriter (jcf, currentClass) {							public void writeOneField (FileWriter outFile, JField subField,													   String sqlName, String preName, 													   boolean isFirst) 								throws IOException, SchemaException {								String subVarName = this.currentClass.getClassName ().substring (0,1).toLowerCase ()									+this.currentClass.getClassName ().substring (1);								preName = subVarName +".get" + this.jcf.getGetSet () + " ().get";													String set_type = findSetType (subField);								String endMod = "";								if (subField.isDate ()) set_type = "Timestamp";								else if (subField.getObjectType ().equals ("boolean")) {									set_type = "String";									endMod = "? \"T\" : \"F\"";								}								if (subField.getObjectType().equals ("Boolean")) {									outFile.write ("\t\tstmt.setString (i++, "+														  "getBooleanAsString("+														  preName + subField.getGetSet () 														  + " ())" + endMod + ");\n");								} else									outFile.write ("\t\tstmt.set" + set_type +  " (i++, "+														  preName + subField.getGetSet () + " ()" 														  + endMod + ");\n");							}						};					iw.execute (factoryOutFile, false);					/*										JClass fieldClass = jcf.getJClass ();					Vector fields = new Vector (fieldClass.getAllFields ().values ());					String subPrimaryKey = fieldClass.getPrimaryKey ();					String prefix = jcf.getPrefix ();					for (int j = 0; j < fields.size (); j++) {					JField subField = (JField)fields.elementAt (j);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -