3.8.2. Reverse Mapping
OpenJPA includes a reverse mapping tool for generating persistent class definitions, complete with metadata, from an existing database schema. You do not have to use the reverse mapping tool to access an existing schema; you are free to write your classes and mappings yourself, as described in Meet-in-the-Middle Mapping. The reverse mapping tool, however, can give you an excellent starting point from which to grow your persistent classes.
To use the reverse mapping tool, follow the steps below:
-
Use the schema tool to export your current schema to an XML schema file. You can skip this step and the next step if you want to run the reverse mapping tool directly against the database.
java org.apache.openjpa.jdbc.schema.SchemaTool -a reflect -f schema.xml
-
Examine the generated schema file. JDBC drivers often provide incomplete or faulty metadata, in which case the file will not exactly match the actual schema. Alter the XML file to match the true schema. The XML format for the schema file is described in XML Schema Format.
After fixing any errors in the schema file, modify the XML to include foreign keys between all relations. The schema tool will have automatically detected existing foreign key constraints; many schemas, however, do not employ database foreign keys for every relation. By manually adding any missing foreign keys, you will give the reverse mapping tool the information it needs to generate the proper relations between the persistent classes it creates. . Run the reverse mapping tool on the finished schema file. If you do not supply the schema file to reverse map, the tool will run directly against the schema in the database. The tool can be run via its Java class, org.apache.openjpa.jdbc.meta.ReverseMappingTool.
java org.apache.openjpa.jdbc.meta.ReverseMappingTool -pkg com.xyz -d ~/src -cp customizer.properties schema.xml
In addition to OpenJPA’s standard configuration flags, including code formatting options, the reverse mapping tool recognizes the following command line arguments:
-
-schemas/-s <schema and table names>: A comma-separated list of schema and table names to reverse map, if no XML schema file is supplied. Each element of the list must follow the naming conventions for theopenjpa.jdbc.Schemasproperty described in Schemas List. In fact, if this flag is omitted, it defaults to the value of theSchemasproperty. If theSchemasproperty is not defined, all schemas will be reverse-mapped. -
-package/-pkg <package name>: The package name of the generated classes. If no package name is given, the generated code will not contain package declarations. -
-directory/-d <output directory>: All generated code and metadata will be written to the directory at this path. If the path does not match the package of a class, the package structure will be created beneath this directory. Defaults to the current directory. -
-metadata/-md <class | package | none>: Specify the level the metadata should be generated at. Defaults to generating a single package-level metadata file. Set tononeto disable orm.xml generation. -
-annotations/-ann <true/t | false/f>: Set totrueto generate JPA annotations in generated Java classes. -
-accessType/-access <field | property>: Change access type for generated annotations. Defaults to field access. -
-useSchemaName/-sn <true/t | false/f>: Set this flag totrueto include the schema as well as table name in the name of each generated class. This can be useful when dealing with multiple schemas with same-named tables. -
-useSchemaElement/-se <true/t | false/f>: Set this flag tofalseto exclude the schema name from the@Tableannotation in the generated class for each table. If set tofalse, the schema name will also be removed from the corresponding XML mapping files (orm.xml) that are generated by the tool. The initialized value is true (in order to preserve backwards compatibility). -
-useForeignKeyName/-fkn <true/t | false/f>: Set this flag totrueif you would like field names for relations to be based on the database foreign key name. By default, relation field names are derived from the name of the related class. -
-nullableAsObject/-no <true/t | false/f>: By default, all non-foreign key columns are mapped to primitives. Set this flag totrueto generate primitive wrapper fields instead for columns that allow null values. -
-blobAsObject/-bo <true/t | false/f>: By default, all binary columns are mapped tobyte[]fields. Set this flag totrueto map them toObjectfields instead. Note that when mapped this way, the column is presumed to contain a serialized Java object. -
-primaryKeyOnJoin/-pkj <true/t | false/f>: The standard reverse mapping tool behavior is to map all tables with primary keys to persistent classes. If your schema has primary keys on many-many join tables as well, set this flag totrueto avoid creating classes for those tables. -
-inverseRelations/-ir <true/t | false/f>: Set tofalseto prevent the creation of inverse 1-many/1-1 relations for every many-1/1-1 relation detected. -
-useGenericCollections/-gc <true/t | false/f>: Set to true to use generic collections on OneToMany and ManyToMany relations. -
-useDatastoreIdentity/-ds <true/t | false/f>: Set totrueto use datastore identity for tables that have single numeric primary key columns. The tool typically uses application identity for all generated classes. -
-useBuiltinIdentityClass/-bic <true/t | false/f>: Set tofalseto prevent the tool from using built-in application identity classes when possible. This will force the tool to create custom application identity classes even when there is only one primary key column. -
-innerIdentityClasses/-inn <true/t | false/f>: Set totrueto have any generated application identity classes be created as static inner classes within the persistent classes. Defaults tofalse. -
-identityClassSuffix/-is <suffix>: Suffix to append to class names to form application identity class names, or for inner identity classes, the inner class name. Defaults toId. -
-typeMap/-typ <type mapping>: A string that specifies the default Java classes to generate for each SQL type that is seen in the schema. The format isSQLTYPE1=JavaClass1,SQLTYPE2=JavaClass2. The SQL type name first looks for a customization based onSQLTYPE(SIZE,PRECISION), thenSQLTYPE(SIZE), thenSQLTYPE. So if a column whose type name isCHARis found, it will first look for theCHAR(50,0)type name specification, then it will look forCHAR(50), and finally it will just look forCHAR. For example, to generate a char array for everyCHARcolumn whose size is exactly 50, and to generate ashortfor every type name ofINTEGER, you might specify:CHAR(50)=char[],INTEGER=short. Note that since various databases report different type names differently, one database’s type name specification might not work for another database. EnableTRACElevel logging on theMetaDatachannel to track which type names OpenJPA is examining. -
-customizerClass/-cc <class name>: The full class name of a org.apache.openjpa.jdbc.meta.ReverseCustomizer customization plugin. If you do not specify a reverse customizer of your own, the system defaults to a PropertiesReverseCustomizer. This customizer allows you to specify simple customization options in the properties file given with the-customizerPropertiesflag below. We present the available property keys below. -
-customizerProperties/-cp <properties file or resource>: The path or resource name of a properties file to pass to the reverse customizer on initialization. -
-customizer./-c.<property name> <property value>: The given property name will be matched with the corresponding Java bean property in the specified reverse customizer, and set to the given value.
Running the tool will generate .java files for each generated class (and its application identity class, if applicable), along with JPA annotations (if enabled by setting -annotations true), or an orm.xml file (if not disabled with -metadata none) containing the corresponding persistence metadata.
. Examine the generated class, metadata, and mapping information, and modify it as necessary. Remember that the reverse mapping tool only provides a starting point, and you are free to make whatever modifications you like to the code it generates.
After you are satisfied with the generated classes and their mappings, you should first compile the classes with javac, jikes, or your favorite Java compiler.
Make sure the classes are located in the directory corresponding to the -package flag you gave the reverse mapping tool.
Next, if you have generated an orm.xml, move that file to a META-INF directory within a directory in your classpath.
Finally, enhance the classes if necessary (see Enhancement).
Your persistent classes are now ready to access your existing schema.