Bug? Hbm2javatask cannot implement joined-subclass individual configuration file (2.1.2)

Source: Internet
Author: User
Tags object extend final generator net one table throwable tostring

It is not necessary to read this article if you do not intend to use the class inheritance structure. Read another article I wrote "Using the Hibernate extension tool Hbm2javatask generate a Persistent object class (2.1.2) based on a profile" 1. In the 8th chapter of the document (hibernate/doc/reference/zh-cn/html/ inheritance.html) has mentioned

The mapping for "one table per subclass" Is this:

<class name= "Payment" table= "Payment" > <id name= "id" type= "long" column= "payment_id" > <generator class= "Native"/> </id> <property name= "Amount" column= "Amount"/> ... <joined-subclass name= " Creditcardpayment "table=" credit_payment > <key column= "payment_id"/> ... </joined-subclass> < Joined-subclass name= "cashpayment" table= "cash_payment" > <key column= "payment_id"/> ... </ joined-subclass> <joined-subclass name= "chequepayment" table= "cheque_payment" > <key column= "PAYMENT_ID" /> ... </joined-subclass></class>

2. The document 5th chapter (hibernate/doc/reference/zh-cn/html/mapping.html) mentions

Allows you to define subclass and Joined-subclass in a stand-alone mapping document, directly under Hibernate-mapping. This allows you to add a new mapping file each time you expand your class hierarchy. In the mapping of subclasses you must specify a extents attribute that indicates a superclass that has previously been mapped. When using this feature, be sure to note that the mapping of the file is very important!

3. According to the above two points, I created a project according to the 8th chapter of Payment, Joined-subclass moved out, now the engineering directory structure is as follows Payment &NBSP;&LT;DIR&GT;|-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. This article no longer repeats the contents of Build.xml, Hibernate.codegen.xml, log4j.properties three files. You can view the contents of these three files in the article, "Using the Hibernate extension tool Hbm2javatask generate a Persistent object class (2.1.2) from a profile." Only the. hbm.xml file contents are listed here.   4.1 payment.hbm.xml<?xml version= "1.0" encoding= "GBK"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping dtd//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-2.0.dtd "><?xml version= "1.0" encoding= "GBK"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping dtd//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-2.0.dtd ">4.3 CashPayment.hbm.xml
<?xml version= "1.0" encoding= "GBK"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping dtd//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-2.0.dtd ">5. In the command line into the engineering directory, run ant, Error, the key prompts are as follows: Net.sf.hibernate.MappingException:Cannot extend unmapped class payment.   Payment6. I will not say the wrong process, more boring, just say the problem where the 6.1 hbm2javatask in the list of profiles to do a loop, each file separately processing, so there are associated classes can not find. 6.2 But the CodeGenerator class is also inappropriate and does not consider file routing issues, because subclasses may be processed before the parent class. 7. Below is a list of two modified file codes.  Added a Chinese annotation to the place where it was modified. 7.1 Net.sf.hibernate.tool.hbm2java.Hbm2JavaTask
Package Net.sf.hibernate.tool.hbm2java;import Java.io.file;import Java.io.printwriter;import java.io.StringWriter; Import Java.util.arraylist;import Java.util.list;import Org.apache.tools.ant.buildexception;import Org.apache.tools.ant.directoryscanner;import Org.apache.tools.ant.task;import Org.apache.tools.ant.types.FileSet ; Import Org.apache.tools.ant.types.path;import Org.apache.tools.ant.types.reference;import Org.apache.commons.logging.log;import org.apache.commons.logging.logfactory;/** * Task for Hbm2java (Hibernates CodeGenerator * * * @author Gbegley and Max * */public class Hbm2javatask extends Task {private static final log = L Ogfactory.getlog (Codegenerator.class); Private File ConfigurationFile; Private Path Compileclasspath; Private File OutputDir; Private List filesets = new ArrayList (); /** * Set A hbm2java <literal>config.xml</literal> configuration file * @param the file name */public void SE Tconfig (File configurationfile) {this.configurationfile = CoNfigurationfile; }/** * Set the classpath to is used for this compilation. * * @param classpath an Ant Path object containing the compilation classpath. */public void Setclasspath (Path classpath) {if (Compileclasspath = = null) {Compileclasspath = Classpath;} else {Compi Leclasspath.append (CLASSPATH); }/** Gets the classpath to is used for this compilation. * * Public Path Getclasspath () {return compileclasspath;}/** * Adds a path to the classpath. */Public Path Createclasspath () {if (Compileclasspath = = null) {Compileclasspath = new path (Getproject ()); Pileclasspath.createpath (); }/** * Adds a reference to a classpath defined elsewhere. */public void Setclasspathref (Reference r) {Createclasspath (). Setrefid (R);}/** * Adds a set of files to translate. */public void Addfileset (Fileset set) {Filesets.add (set);}/** * Sets the output directory. * * @param bindirectory directory */public void Setoutput (File outdirectory) {this.outputdir = outdirectory;} puBlic void Execute () throws Buildexception {List filelist = Gettargetfiles (); if (filelist.size () = 0) return; log ("Proce Ssing "+ filelist.size () +" files. "); try {log ("Building Hibernate objects");//This loop is Error 1,//for (int i = 0; i < filelist.size (); i++) {//Processfile (OUTPU Tdir, (File) filelist.get (i)); //To modify the Processfile method Processfile (OutputDir, filelist); catch (Throwable t) {stringwriter SW = new StringWriter (); T.printstacktrace (new PrintWriter (SW)); throw new Buildexcep tion ("caused by:\n" + sw.tostring ()); }/** * * * * * Comment: * The initial ant task had some initial on the filtering Hbm.xml/java to only process the names ded files. * That isn't possible to decide in the ant task without implementing the same logic in present. * Thus I ' ve removed it and let it is something that Hbm2java should do. * * * @return/Private list gettargetfiles () {List L = new java.util.ArrayList ();//deal with the filesets for (int i = 0; I < filesets.size (); i++) { Fileset fs = (fileset) filesets.get (i); File parent = Fs.getdir (Getproject ()); DirectoryScanner ds = Fs.getdirectoryscanner (Getproject ()); string[] files = ds.getincludedfiles (); for (int j = 0; J < Files.length; J +) {file Srcfile = new File (parent, files[j]); L.add (srcfile);} return l; //modified method parameter private void Processfile (File outputdir, List filelist) {List args = new ArrayList (); if (OutputDir!= null) {Args.add ("--output=" + Outputdir.getabsolutepath ());} if (configurationfile!= null) {Args.add ("--config=" + configurationfile);//Add all files to command-line arguments for (int i = 0; i < fil Elist.size (); i++) {Args.add ((File) filelist.get (i)). GetAbsolutePath ());} try { Net.sf.hibernate.tool.hbm2java.CodeGenerator.main ((string[]) Args.toarray (new String[args.size ())); catch (Throwable t) {stringwriter SW = new StringWriter (); T.printstacktrace (new PrintWriter (SW)); throw new Buildexcep tion ("caused by:\n" + sw.tostring ()); } }}
7.2 Net.sf.hibernate.tool.hbm2java.CodeGenerator
* * $Id: codegenerator.java,v 1.7 2004/03/22 20:41:47 maxcsaucdk Exp $ */package net.sf.hibernate.tool.hbm2java;import ja Va.io.file;import java.util.arraylist;import java.util.hashmap;import Java.util.iterator;import java.util.List; Import Net.sf.hibernate.mappingexception;import Net.sf.hibernate.util.dtdentityresolver;import Org.apache.commons.collections.multihashmap;import Org.apache.commons.collections.multimap;import Org.apache.commons.logging.log;import Org.apache.commons.logging.logfactory;import Org.jdom.Document;import Org.jdom.element;import Org.jdom.input.saxbuilder;import Org.xml.sax.errorhandler;import org.xml.sax.saxparseexception;/** * */public class CodeGenerator {private static final log = Logfactory.getlog (codege Nerator.class); public static void Main (string[] args) {if (args.length==0) {System.err.println ("No arguments provided. Nothing todo. Exit. "); System.exit (-1); try {ArrayList mappingfiles = new ArrayList (); Saxbuilder builder = new Saxbuilder (true);Builder.setentityresolver (New Dtdentityresolver ()); Builder.seterrorhandler (New ErrorHandler () {public void error (saxparseexception error) {log.error ("Error parsing XML:" + error.getsystemid () + ' (' + error.getlinenumber () + ') ', error); public void FatalError (saxparseexception error) {error (Error),} public void Warning (saxparseexception error) {Log.war N ("Warning parsing XML:" + error.getsystemid () + ' (' + error.getlinenumber () + ') ');}); String OutputDir = null; List generators = new ArrayList (); Multimap Globalmetas = new Multihashmap (); Parse command line parameters for (int i = 0; i < args.length; i++) {if (Args[i].startswith ("--)") {if (args[i].s Tartswith ("--config=")) {//parse config XML file builder.setvalidation (false); Document document = Builder.build (New File (args[i].substring (9)); Globalmetas = Metaattributehelper.loadandmergemetamap (document.getrootelement (), NULL); Iterator generateelements = Document.getrootelement (). GetChildren ("Generate"). iterator (); while (Generateelements.hasnext ()) {Generators.add (new generator (Element) Generateelements.next ());} Builder.setv Alidation (TRUE); else if (Args[i].startswith ("--output=")) {OutputDir = args[i].substring (9);}} else {mappingfiles.add (args[i]);} If no config XML file, add a default generator if (generators.size () = = 0) {Generators.add (New generator ());} HashMap classmappings = new HashMap (); Builder.setvalidation (TRUE); This loop is error 2//changed to only process class mappings for (iterator iter = Mappingfiles.iterator (); Iter.hasnext ();) {//Parse the mapping file File = new file ((String) Iter.next ()); Log.debug (File.getabsolutepath ()); Document document = Builder.build (file); Element rootelement = Document.getrootelement (); Org.jdom.Attribute a = Rootelement.getattribute ("package"); String pkg = null; if (a!=null) {pkg = A.getvalue ();} Mappingelement me = new Mappingelement (rootelement, Null/**todo-hbm2java:-should be config.xml**/); Iterator classelements = rOotelement.getchildren ("class"). Iterator (); Multimap mm = Metaattributehelper.loadandmergemetamap (rootelement, Globalmetas); Handleclass (Pkg,me, Classmappings, Classelements, MM, false); //Copy previous loop//process subclass and Joined-class mappings for (iterator iter = Mappingfiles.iterator (); Iter.hasnext ();) {//Parse the mapping file File = new file ((String) Iter.next ()); Document document = Builder.build (file); Element rootelement = Document.getrootelement (); Org.jdom.Attribute a = Rootelement.getattribute ("package"); String pkg = null; if (a!=null) {pkg = A.getvalue ();} Mappingelement me = new Mappingelement (rootelement, Null/**todo-hbm2java:-should be config.xml**/); Multimap mm = Metaattributehelper.loadandmergemetamap (rootelement, Globalmetas); Iterator classelements = Rootelement.getchildren ("Subclass"). iterator (); Handleclass (Pkg,me,classmappings, Classelements, MM, true); Classelements = Rootelement.getchildren ("Joined-subclass"). iterator (); Handleclass (Pkg,me,classmappings, ClasSelements, MM, true); ///Generate source files for (iterator iterator = Generators.iterator (); Iterator.hasnext ();) {Generator G = (generator) iterator.next (); G.setbasedirname (OutputDir); g.generate (classmappings);} catch (Exception e) {e.printstacktrace ();}} private static void Handleclass (String classpackage, mappingelement me, HashMap classmappings, iterator classelements, Mu Ltimap mm, Boolean Extendz) throws Mappingexception {while (Classelements.hasnext ()) {Element clazz = (Element) classe Lements.next (); if (!extendz) {classmapping cmap = new Classmapping (Classpackage, Clazz, Me, mm); Classmappings.put ( Cmap.getfullyqualifiedname (), CMAP); else {String ex = Clazz.getattributevalue ("extends"); if (ex==null) {throw new Mappingexception ("Missing extends attrib Ute on < "+ clazz.getname () +" name= "+ clazz.getattributevalue (" name ") +" > "); } classmapping superclass = (classmapping) classmappings.get (ex); if (superclass = = null) {throw new Mappingexception ("CannOT extend unmapped class "+ ex";} classmapping subclassmapping = new Classmapping (Classpackage, Me, Superclass.getclassname (), superclass, clazz, MM); Superclass.addsubclass (subclassmapping); } } }}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.