|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
手机用到的是用j2me所编出来的小程序。
假如你其实不盘算利用类承继布局并非很有需要浏览本文。请先浏览我写的另外一篇文章"利用hibernate扩大工具Hbm2JavaTask依据设置文件天生耐久化对象类(2.1.2)"1.在文档第8章(hibernate/doc/reference/zh-cn/html/inheritance.html)有提到
“每一个子类一个表”的映照是如许的:
<classname="Payment"table="PAYMENT"><idname="id"type="long"column="PAYMENT_ID"><generatorclass="native"/></id><propertyname="amount"column="AMOUNT"/>...<joined-subclassname="CreditCardPayment"table="CREDIT_PAYMENT"><keycolumn="PAYMENT_ID"/>...</joined-subclass><joined-subclassname="CashPayment"table="CASH_PAYMENT"><keycolumn="PAYMENT_ID"/>...</joined-subclass><joined-subclassname="ChequePayment"table="CHEQUE_PAYMENT"><keycolumn="PAYMENT_ID"/>...</joined-subclass></class>
2.文档第5章(hibernate/doc/reference/zh-cn/html/mapping.html)有提到
同意在自力的映照文档中界说subclass和joined-subclass,间接位于hibernate-mapping下。这就能够让你每次扩大你的类条理的时分,到场新的映照文件就好了。在子类的映照中你必需指定一个extents属性,指明先前已映照过的超类。利用这个功效的时分,必定要注重映照文件的排序长短常主要的!
<hibernate-mapping><subclassname="eg.subclass.DomesticCat"extends="eg.Cat"discriminator-value="D"><propertyname="name"type="string"/></subclass></hibernate-mapping>
3.依据以上两点,偶依据第8章的PAYMENT创立了一个工程,把joined-subclass移了出来,如今工程目次布局以下Payment<dir>|-src<dir>|-hbm<dir>|-payment<dir>|-Payment.hbm.xml|-CreditCardPayment.hbm.xml|-CashPayment.hbm.xml|-classes<dir>|-lib<dir>|-build.xml|-hibernate.codegen.xml|-log4j.properties4.本文不再反复build.xml,hibernate.codegen.xml,log4j.properties三个文件的内容。可在"利用hibernate扩大工具Hbm2JavaTask依据设置文件天生耐久化对象类(2.1.2)"一文检察这三个文件的内容。此处仅列出.hbm.xml文件内容。4.1Payment.hbm.xml<?xmlversion="1.0"encoding="gbk"?><!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD//EN""http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"><hibernate-mapping><classname="payment.Payment"table="PAYMENT"><idname="id"type="long"column="PAYMENT_ID"><generatorclass="native"/></id><propertyname="amount"column="AMOUNT"type="long"/></class></hibernate-mapping>4.2CreditCardPayment.hbm.xml
<?xmlversion="1.0"encoding="gbk"?><!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD//EN""http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"><hibernate-mapping><joined-subclassname="payment.CreditCardPayment"table="CREDIT_PAYMENT"extends="payment.Payment"><keycolumn="PAYMENT_ID"/></joined-subclass></hibernate-mapping>
4.3CashPayment.hbm.xml
<?xmlversion="1.0"encoding="gbk"?><!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD//EN""http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"><hibernate-mapping><joined-subclassname="payment.CashPayment"table="CASH_PAYMENT"extends="payment.Payment"><keycolumn="PAYMENT_ID"/></joined-subclass></hibernate-mapping>
5.在命令行进进工程目次,运转ant,产生毛病,关头提醒以下:net.sf.hibernate.MappingException:Cannotextendunmappedclasspayment.Payment6.查错历程我就不说了,对照无聊,只说一下成绩出在那里6.1Hbm2JavaTask里对设置文件列表做了轮回,每一个文件独自处置,以是有联系关系的类就找不到了。6.2可是CodeGenerator类也有不当,没有思索文件分列成绩,由于子类大概先于父类被处置。7.上面帖出两个修正过的文件代码。在修正的中央加了中文正文。7.1net.sf.hibernate.tool.hbm2java.Hbm2JavaTask
packagenet.sf.hibernate.tool.hbm2java;importjava.io.File;importjava.io.PrintWriter;importjava.io.StringWriter;importjava.util.ArrayList;importjava.util.List;importorg.apache.tools.ant.BuildException;importorg.apache.tools.ant.DirectoryScanner;importorg.apache.tools.ant.Task;importorg.apache.tools.ant.types.FileSet;importorg.apache.tools.ant.types.Path;importorg.apache.tools.ant.types.Reference;importorg.apache.commons.logging.Log;importorg.apache.commons.logging.LogFactory;/***Taskforhbm2java(Hibernatescodegenerator)***@authorGBegleyandmax**/publicclassHbm2JavaTaskextendsTask{privatestaticfinalLoglog=LogFactory.getLog(CodeGenerator.class);privateFileconfigurationFile;privatePathcompileClasspath;privateFileoutputDir;privateListfilesets=newArrayList();/***Setahbm2java<literal>config.xml</literal>configurationfile*@paramthefilename*/publicvoidsetConfig(FileconfigurationFile){this.configurationFile=configurationFile;}/***Settheclasspathtobeusedforthiscompilation.**@paramclasspathanAntPathobjectcontainingthecompilationclasspath.*/publicvoidsetClasspath(Pathclasspath){if(compileClasspath==null){compileClasspath=classpath;}else{compileClasspath.append(classpath);}}/**Getstheclasspathtobeusedforthiscompilation.*/publicPathgetClasspath(){returncompileClasspath;}/***Addsapathtotheclasspath.*/publicPathcreateClasspath(){if(compileClasspath==null){compileClasspath=newPath(getProject());}returncompileClasspath.createPath();}/***Addsareferencetoaclasspathdefinedelsewhere.*/publicvoidsetClasspathRef(Referencer){createClasspath().setRefid(r);}/***Addsasetoffilestotranslate.*/publicvoidaddFileset(FileSetset){filesets.add(set);}/***Setstheoutputdirectory.**@parambinDirectorydirectory*/publicvoidsetOutput(FileoutDirectory){this.outputDir=outDirectory;}publicvoidexecute()throwsBuildException{ListfileList=getTargetFiles();if(fileList.size()==0)return;log("Processing"+fileList.size()+"files.");try{log("Buildinghibernateobjects");//这个轮回是毛病1,//for(inti=0;i<fileList.size();i++){//processFile(outputDir,(File)fileList.get(i));//}//要修正processFile办法processFile(outputDir,fileList);}catch(Throwablet){StringWritersw=newStringWriter();t.printStackTrace(newPrintWriter(sw));thrownewBuildException("Causedby:
"+sw.toString());}}/*****Comment:*Theinitialanttaskhadsomeinitialfilteringonthehbm.xml/javanamestoonlyprocesstheneededfiles.*Thatisnotpossibletodecideintheanttaskwithoutimplementingthesamelogicpresentinhbm2java.*ThusIveremoveditandletitbesomethingthathbm2javashoulddo.***@return*/privateListgetTargetFiles(){Listl=newjava.util.ArrayList();//dealwiththefilesetsfor(inti=0;i<filesets.size();i++){FileSetfs=(FileSet)filesets.get(i);Fileparent=fs.getDir(getProject());DirectoryScannerds=fs.getDirectoryScanner(getProject());String[]files=ds.getIncludedFiles();for(intj=0;j<files.length;j++){FilesrcFile=newFile(parent,files[j]);l.add(srcFile);}}returnl;}//修正了办法参数privatevoidprocessFile(FileoutputDir,ListfileList){Listargs=newArrayList();if(outputDir!=null){args.add("--output="+outputDir.getAbsolutePath());}if(configurationFile!=null){args.add("--config="+configurationFile);}//把一切文件都到场命令行参数for(inti=0;i<fileList.size();i++){args.add(((File)fileList.get(i)).getAbsolutePath());}try{net.sf.hibernate.tool.hbm2java.CodeGenerator.main((String[])args.toArray(newString[args.size()]));}catch(Throwablet){StringWritersw=newStringWriter();t.printStackTrace(newPrintWriter(sw));thrownewBuildException("Causedby:
"+sw.toString());}}}
7.2net.sf.hibernate.tool.hbm2java.CodeGenerator
/**$Id:CodeGenerator.java,v1.72004/03/2220:41:47maxcsaucdkExp$*/packagenet.sf.hibernate.tool.hbm2java;importjava.io.File;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.Iterator;importjava.util.List;importnet.sf.hibernate.MappingException;importnet.sf.hibernate.util.DTDEntityResolver;importorg.apache.commons.collections.MultiHashMap;importorg.apache.commons.collections.MultiMap;importorg.apache.commons.logging.Log;importorg.apache.commons.logging.LogFactory;importorg.jdom.Document;importorg.jdom.Element;importorg.jdom.input.SAXBuilder;importorg.xml.sax.ErrorHandler;importorg.xml.sax.SAXParseException;/****/publicclassCodeGenerator{privatestaticfinalLoglog=LogFactory.getLog(CodeGenerator.class);publicstaticvoidmain(String[]args){if(args.length==0){System.err.println("Noargumentsprovided.Nothingtodo.Exit.");System.exit(-1);}try{ArrayListmappingFiles=newArrayList();SAXBuilderbuilder=newSAXBuilder(true);builder.setEntityResolver(newDTDEntityResolver());builder.setErrorHandler(newErrorHandler(){publicvoiderror(SAXParseExceptionerror){log.error("ErrorparsingXML:"+error.getSystemId()+(+error.getLineNumber()+),error);}publicvoidfatalError(SAXParseExceptionerror){error(error);}publicvoidwarning(SAXParseExceptionerror){log.warn("WarningparsingXML:"+error.getSystemId()+(+error.getLineNumber()+));}});StringoutputDir=null;Listgenerators=newArrayList();MultiMapglobalMetas=newMultiHashMap();//parsecommandlineparametersfor(inti=0;i<args.length;i++){if(args[i].startsWith("--")){if(args[i].startsWith("--config=")){//parseconfigxmlfilebuilder.setValidation(false);Documentdocument=builder.build(newFile(args[i].substring(9)));globalMetas=MetaAttributeHelper.loadAndMergeMetaMap(document.getRootElement(),null);IteratorgenerateElements=document.getRootElement().getChildren("generate").iterator();while(generateElements.hasNext()){generators.add(newGenerator((Element)generateElements.next()));}builder.setValidation(true);}elseif(args[i].startsWith("--output=")){outputDir=args[i].substring(9);}}else{mappingFiles.add(args[i]);}}//ifnoconfigxmlfile,addadefaultgeneratorif(generators.size()==0){generators.add(newGenerator());}HashMapclassMappings=newHashMap();builder.setValidation(true);//这个轮回是毛病2//改成只处置class映照for(Iteratoriter=mappingFiles.iterator();iter.hasNext();){//parsethemappingfileFilefile=newFile((String)iter.next());log.debug(file.getAbsolutePath());Documentdocument=builder.build(file);ElementrootElement=document.getRootElement();org.jdom.Attributea=rootElement.getAttribute("package");Stringpkg=null;if(a!=null){pkg=a.getValue();}MappingElementme=newMappingElement(rootElement,null/**TODO-hbm2java:-shouldbeconfig.xml**/);IteratorclassElements=rootElement.getChildren("class").iterator();MultiMapmm=MetaAttributeHelper.loadAndMergeMetaMap(rootElement,globalMetas);handleClass(pkg,me,classMappings,classElements,mm,false);}//复制了上一个轮回//处置subclass和joined-class映照for(Iteratoriter=mappingFiles.iterator();iter.hasNext();){//parsethemappingfileFilefile=newFile((String)iter.next());Documentdocument=builder.build(file);ElementrootElement=document.getRootElement();org.jdom.Attributea=rootElement.getAttribute("package");Stringpkg=null;if(a!=null){pkg=a.getValue();}MappingElementme=newMappingElement(rootElement,null/**TODO-hbm2java:-shouldbeconfig.xml**/);MultiMapmm=MetaAttributeHelper.loadAndMergeMetaMap(rootElement,globalMetas);IteratorclassElements=rootElement.getChildren("subclass").iterator();handleClass(pkg,me,classMappings,classElements,mm,true);classElements=rootElement.getChildren("joined-subclass").iterator();handleClass(pkg,me,classMappings,classElements,mm,true);}//generatesourcefilesfor(Iteratoriterator=generators.iterator();iterator.hasNext();){Generatorg=(Generator)iterator.next();g.setBaseDirName(outputDir);g.generate(classMappings);}}catch(Exceptione){e.printStackTrace();}}privatestaticvoidhandleClass(StringclassPackage,MappingElementme,HashMapclassMappings,IteratorclassElements,MultiMapmm,booleanextendz)throwsMappingException{while(classElements.hasNext()){Elementclazz=(Element)classElements.next();if(!extendz){ClassMappingcmap=newClassMapping(classPackage,clazz,me,mm);classMappings.put(cmap.getFullyQualifiedName(),cmap);}else{Stringex=clazz.getAttributeValue("extends");if(ex==null){thrownewMappingException("Missingextendsattributeon<"+clazz.getName()+"name="+clazz.getAttributeValue("name")+">");}ClassMappingsuperclass=(ClassMapping)classMappings.get(ex);if(superclass==null){thrownewMappingException("Cannotextendunmappedclass"+ex);}ClassMappingsubclassMapping=newClassMapping(classPackage,me,superclass.getClassName(),superclass,clazz,mm);superclass.addSubClass(subclassMapping);}}}}
IDE是好。java中的IDE更是百花齐放,你用jbuilder能说jbuilder赶不上vs吗?用eclipse,netbeans也很舒服啊。我就不明白“稍微差一些”那一些是从哪里差来的。 |
|