Sample output
Only the code marked with "author: auto-generated" is directly produced from the generator. The rest of the code is merely copied over from a skeleton directory and may be removed from your target application. The main packages to note are:
Access the sample code
HbnPojoGen takes its input from one central configuration. Normally you will edit a provided configuration file to suit your requirements. A minimal config file looks as follows:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<appconfig>
<dbType>MYSQL</dbType>
<driver>com.mysql.jdbc.Driver</driver>
<jdbcConnectionString>jdbc:mysql://127.0.0.1/hbnPojoTest</jdbcConnectionString>
<databaseIP>localhost</databaseIP>
<databaseCatalog>someDBName</databaseCatalog>
<databaseUsername>root</databaseUsername>
<databasePassword>abcdefgh</databasePassword>
<sourceTarget>D:/Workspace/yourProject</sourceTarget>
<projectName>yourProjectName</projectName>
<topLevel>com.yourcompany</topLevel>
<libPath>libs</libPath>
<schemaStrategy>PARTIAL</schemaStrategy>
</appconfig>
The menu on this page also lists additional configuration options you may include.
Requirements
The binary releases have been compiled using JVM version 6. You will need this version (or later) to run it directly.
Alternatively, download the source code and compile it with your favourite compiler. The source code is in a form ready to be loaded as an eclipse project.
You will also need a working MySQL DB and some free space to output the source files.
Usage
HbnPojoGen is not (yet) an eclipse plugin. To use, run the jar file provided together with a config file which you’ll have to customize to your liking as follows:
java -jar hbnPojoGen.jar config.xml
The
configuration file contains everything necessary to generate your source code.
Using the generated code
The generator sets up
Spring, via applicationContext.xml, to provide for the right dependency injection for use in the generated test cases. You might need to modify this file to provide injection support for your application. See Spring documentation for more information about this.
Once setup, usage of the generated code is fairly typical:
SomeTableDao someTableDao = HibernateDaoFactory.getSomeTableDao();
SomeTable someTable = new someTable();
someTable.setFoo(..);
someTableDao.save(someTable);
With the generated data services layer, the code becomes even simpler:
SomeTable someTable = DataServices.getSomeTable(100);
someTable.setFoo(..);
DataServices.save(someTable);
or you might wish to use spring:
@Autowire
SomeTableDao dao;
...
SomeTable someTable = DataServices.getSomeTable(100);
someTable.setFoo(..);
dao.save(sometable);
Remember that the generator also creates a test case for every table in your schema so just have a look at the generated code for examples of saving and retreiving your data. You might also wish to have a look at some
sample output.
News & releases
Upgrading notes:
- The config file requires an additional mandatory parameter: <dbType>
- JUnit jar file has been updated to version 4.4, thus deprecating some methods.
You are strongly encouraged to upgrade from any previous release.
How does it work?
The generator uses JDBC to look at your database metadata to obtain the relationships between the tables, field types and so on. Once this is done, it constructs an object model representing the tables in the java world and thereafter uses Velocity as a templating engine to actually write out your source code.
The whole process, usually lasting just several seconds, is completely automated and requires no further interaction on your part.
What about the generated code?
A lot of work has gone into ensuring the resultant code is free from any errors, warnings or broken conventions. At the end of the run, your target folder will contain:
- A class for each table in your database
- A Data Access Object (+ interface) to access that table
- Enumeration objects pertaining to that class
- Data factories
- JUnit v4 test case per table
- All the relevant hibernate and spring configuration files
- A data services layer containing static methods to access your data (load(..), save(..), etc)
- Other minor stuff like Maven POM files and Ant build files.
Of course, you always have access to both the source code as well as the velocity template files.
I have business logic code...
Keep that in your own services layer. Remember that the generator will build your
data layer for you, it is up to your application to provide higher level abstractions for the rest of your codebase. The code generated is meant to be completely overwritten on each database change; indeed it is recommended that you script your changes in such a way so as to regenerate your data layer automatically on each change.
What does it do?
Given an accessible database schema, the Hibernate POJO Generator produces all the Java code
necessary to access each field in each table via the Hibernate persistence framework. Additionally, the generator also creates all the necessary helper classes and test units for each component.
Typically, invocation of the generator generates source code with
no errors/warnings and test cases that are able to run immediately
without further customizations.
Features
Given a source database, Hibernate POJO Generator (hbnPojoGen)
generates:
- Java objects representing each table using annotations for use
with Hibernate.
- A JUnit test case per table that uses the objects generated to
create, populate, save, retrieve and compare results
- DAO per class
- The appropriate enumeration files
- Spring and hibernate configuration
- DAO layers
- A data factory class per schema to return a pre-populated
object with random data (for boundary checking, database population,
etc)
Also supports
- Join tables including those with additional fields in link
tables
- Polymorphism/inheritance support
- Composite Keys
- One-To-One, many-to-one, many-to-many, etc
- Multiple schema support (4 modes)
- Natural Keys
- Enumerations (including those entries which cannot be mapped cleanly onto the java world)
- A whole bunch of more stuff (see sample.xml)
YourKit is kindly supporting open source projects with its full-featured Java Profiler.
YourKit, LLC is the creator of innovative and intelligent tools for profiling
Java and .NET applications. Take a look at YourKit's leading software products:
YourKit Java Profiler and
YourKit .NET Profiler.
Known Issues
- Although JDBC is meant to hide database differences, each connector driver has its quirks; therefore at the moment, the generator is only known to work correctly on MySQL databases though it has been reported that MS-SQL support looks pretty good too. Support for other databases, notably PostgreSQL, is coming soon. Other databases are as yet untested (submit reports!)
- On MySQL, it is recommended to switch on lower_case_names to 2 prior to creating your database schema so as to have prettier java name conventions. Alternately, should your table/field names contain underscores as separators, the generator will automatically convert these to camelCase.
Version Checking
Suppose you want to make sure that the model code that is generated is only used
on the database schema that was present during code generation stage. In addition
to using hbm2ddl.auto=validate to check your schema via hibernate, you may also
switch on version checking code during run-time. This works by creating a file
in each schema/package that is scanned during startup by Spring like all other
components. This file contains the version number as read during code generation,
which is then checked at runtime to make sure that the database is what we were
expecting.
<versionCheck defaultEnabled="true" defaultTable="db_version" defaultFields="branch, alter_no">
<except schema="someSchema" table="db_version" fields="branch, alter_no" enabled="false"/>
</versionCheck>
where:
- defaultEnabled = enable/disable all version checking for all schemas. Default: true
- defaultTable = table Name to use for each schema so you can have schema1.db_version, schema2.db_version. Default: db_version
- defaultFields = comma-separated list of fields to use during version check. Default: branch, alter_no
-
Except section: Override the default values. Eg: Enable all checks for all
schemas (defaultEnable=true) except schema someSchema.
Hibernate Pojo Generator offers Maven support in two ways: it allows you to set the
target folders (eg src/main/java - see
Package naming) and is able to create pom files.
Note that enabling maven support also implies that the default output folders will change to reflect the ones normally used by maven (src/main/java etc).
<maven enabled="true" artifactId="some-artifact" groupId="com.yourcompany" version="1.3" name="Some friendly name">
<dependencies><![CDATA[
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.6</version>
</dependency>]]>
</dependencies>
<distributionManagement>
<![CDATA[
<repository>
<id>someid</id>
<name>somename</name>
<url>http://some.url.here/archiva/repository/</url>
</repository>
]]>
</distributionManagement>
</maven>
To enable maven support, make sure that you have specified enabled="true" in the <maven> tag.
The version, artifactIds and other attributes are copied over to the appropriate sections in
your resultant pom.xml file. Use the <dependencies> and <distributionManagement>
sections to copy over segments to your maven configuration file.
Note: At time of writing, the Hibernate artifact must be specified in the config file
(this is due to Hibernate not yet having merged in some important bug fixes). When the Hibernate
team release a corrected version, this will go away. Alternatively, add the required item in
the template file (templates/pom.vm).
Disabling backlinks
Use the disableBackLinks section to specify that the generator should not generate
inverse links in the case of one-to-many/many-to-one links.
For example if table A contains a link to table B, you'll obtain
ClassA.getB() but not ClassB.getAs(). "*" wildcards are allowed implying
"any" (see examples below)
<disableBackLinks>
<nobacklink from="schemaA.*" to="schemaB.*" from-field="*" />
<nobacklink from="*.*" to="*.country" from-field="*" />
<nobacklink from="schemaA.sometable" to="schemaB.linkedtable" from-field="somefield" />
</disableBackLinks>
Data pool factory backlinks
Set disableBackLinksInDataPoolFactory to true to prevent the datapool
factory from returning objects with backlinks. The default is to make
calls such as obj.addXXX(B) rather than b.setXXX(obj)
Example:
<disableBackLinksInDataPoolFactory>false</disableBackLinksInDataPoolFactory>
Custom Annotations and Custom Code
You can opt to add any custom annotations to properties, classes, method getters or method setters. Simply specify the class, your annotations and the location where you wish your annotation to reside. You
may also "paste in" additional code in the generated classes. For example you might have:
public void setName(String name) {
this.Name = name;
}
changed to
public void setName(String name) {
if (name.equals("")) throw new IllegalArgumentException(...);
this.Name = name;
}
You may also add any code you wish at the end of any generated class, add additional
imports or make your class implement any number of interfaces.
You may also use wildcards in the classname definition eg *.yourclass, yourschema.* or *.*
<annotations>
<class name="someClassName">
<imports>
<import>your.custom.import</import>
<import>your.custom.import2</import>
</imports>
<implements>
<interface>someInterface</interface>
<interface>someOtherInterface</interface>
</implements>
<classAnnotation><![CDATA[@yourcustomAnnotation]]></classAnnotation>
<customClassCode>
</customClassCode>
<property name="Amount">
<annotation type="property">foo on prop</annotation>
<annotation type="getter">bar on getter</annotation>
<annotation type="setter">blah on setter</annotation>
<annotation type="getterprecondition"><![CDATA[ logger.debug("About to enter getter method"); ]]></annotation>
<annotation type="setterprecondition">
<![CDATA[
if (foo.equals("")) throw new IllegalArgumentException();
]]>
</annotation>
<annotation type="getterpostcondition"><![CDATA[ logger.debug("Exiting getter method"); ]]></annotation>
<annotation type="setterpostcondition"><![CDATA[ logger.debug("Exiting method"); ]]></annotation>
</property>
</class>
</annotations>
Output suppression
Sometimes you may wish to package your code in such a way so as to import classes
of a schema from somewhere else. The <noOutputForSchema> section specifies that,
though everything should be processed as usual, no files for the schemas listed
below should be generated. This is especially useful in conjunction with <disableBackLinks>.
<noOutputForSchema>
<ignore>someSchema</ignore>
</noOutputForSchema>
Package Naming
By default the generator will opt for a certain package style as follows:
com.yourcompany.yourProjectName.model.obj.SchemaName
You may opt to change this pattern to your liking by using the <dbPackageMap> configuration section as in the following example:
<dbPackageMap>
<map schema="DEFAULT">
<!-- Location of hibernate objects. -->
<objectPackage>${topLevel}.${projectName}.model.obj.${DB}</objectPackage>
<!-- Location of interface for hibernate objects. -->
<objectInterfacePackage>${topLevel}.${projectName}.model.obj.${DB}</objectInterfacePackage>
<!-- Location of hibernate DAO objects. -->
<daoPackage>${topLevel}.${projectName}.model.dao.${DB}</daoPackage>
<daoImplPackage>${topLevel}.${projectName}.model.dao.impl.${DB}</daoImplPackage>
<!-- Location of hibernate enum objects. -->
<enumPackage>${topLevel}.${projectName}.enums.db.${DB}</enumPackage>
<!-- Location of hibernate factory objects. -->
<factoryPackage>${topLevel}.${projectName}.factories.${DB}</factoryPackage>
<!-- Location of data layer objects. -->
<dataPackage>${topLevel}.${projectName}.services.data</dataPackage>
</map>
<map schema="yourschema">
<objectPackage>${topLevel}.yourschema.model</objectPackage>
<objectInterfacePackage>${topLevel}.yourschema.model</objectInterfacePackage>
<daoPackage>${topLevel}.yourschema.model.dao</daoPackage>
<daoImplPackage>${topLevel}.yourschema.model.dao.impl</daoImplPackage>
<enumPackage>${topLevel}.yourschema.enums.db</enumPackage>
<factoryPackage>${topLevel}.yourschema.factories</factoryPackage>
<dataPackage>${topLevel}.yourschema.services.data</dataPackage>
</map>
</dbPackageMap>
This specifies that for the schema named "yourschema", the objects, dao (and others) are pushed out to something like:
com.yourcompany.yourschema.model
while for all other schemas not defined, the default package naming should apply.
Target folders
The default top level folder for the main sources is "src" to match with a typical
eclipse project. You may opt to change this by using the <sourceFolderName> option.
For example, when using maven, you would add the following in your config file:
<sourceFolderName>src/main/java</sourceFolderName>
Similarly, you may change the the location of your unit tests and location
of your applicationContext filename as listed below (typical maven setups below):
<testFolderName>src/test/java</testFolderName>
<applicationContextFilename>src/main/resources/applicationContext.xml</applicationContextFilename>
Enum Configuration
Normally enums are handled completely automatically for you. You do have two configuration options at your disposal.
Firstly, some enums can be common across multiple tables and you might wish to collapse the enums into one. To
do this simply list the enums you want coalesced as follows:
<coalesceEnums>
<schema name="yourschema">
<enum name="YourEnumName">
<field>table1.fieldname1</field>
<field>table2.fieldname5</field>
</enum>
</schema>
</coalesceEnums>
Under MySQL and possibly under other databases, altering an enum definition for an existing table is an expensive
operation leading to unacceptable downtime in some circumstances. As a workaround to this problem, you can
define a table to contain your enum values and instruct the generator to treat that table as a source of
enum values. Therefore while from a programming point of view you would still be dealing with an enum class,
internally the values would have been obtained from the external table.
Use keyColumnName/valueColumnName to specify the exact rows you want otherwise columns 1 and 2 are used.
You may also specify additional columns to map into an enum by the "otherColumnNames". For
example you may have rows like: 1, "Full Match", 100 representing column names ID, Enum name, Weight.
This would then generate appropriate reverse lookup maps for easy access to the enum.
If you want this, create a table
containing at least two columns (an id and the value to use) and specify your requirements using the following
configuration:
<treatLinkAsEnum>
<schema name="yourschema">
<field src="tablename.fieldName" dstTable="tableContainingEnums" />
</schema>
</treatLinkAsEnum>
Ignoring tables
If you want to completely ignore generating code for particular tables, use the <ignore> section to specify one or more tables to skip parsing as follows:
<ignore>
<table>*.authLog</table>
<table>myschema.mytable</table>
</ignore>
This specifies that the authLog table, found in any schema, and mytable found in myschema are to be skipped.
OneToOne mappings
Use the <oneToOne> section to specify fields that are to be treated as one-to-one mappings rather than many-to-one mappings:
<oneToOne>
<table name="someschema.sometable" field="someFieldName" />
</oneToOne>
License
This project is licensed under LGPLv3 or any later version. For more information, redirect your browser to
here
Join (a.k.a Link) tables
Tables intended as link tables cannot be automatically determined simply by looking at the database metadata. Specifying them in the configuration file will make the generator produce alternate code. When you specify link tables, different code is produced depending on whether your link table contains additional fields apart from those mandatory to link two tables together.
If there are only two fields present in the link table, (+ an optional primary key), the generator will use annotations to specify the link table on both ends of the link, therefore you will not have direct access to the link table. Hibernate will completely handle the link table for you.
If additional fields are present in the link table, apart from the usual ManyToOne and OneToMany annotations from each side of the link, the generator will also create additional code to allow each side to map directly to the other link side without having to deal with the intermediate link table.
A link table is defined as follows:
<linktables>
<table name="yourcatalog.UserBillingMap">
<link srcField="userId" dstField="billingId"/>
</table>
</linktables>
Switching the srcField with the dstField parameter only changes which side is markesd as "inverse". See the hibernate documentation for more details.
Preventing Cleaning of tables
The generated testcode contains routines to clear out all the database of the generated code prior to commencing tests. Some tables, for example, a table containing a list of countries, are intended to be read-only and pre-populated by your DBA. Specifying the <preventclean> section will prevent the generator from attempting to delete the specified tables during a test run.
<preventclean>
<table>yourschema.currencyCodes</table>
</preventclean>
Additionally, you may instruct the generator to omit test code that normally clears out a database during the
unit tests as follows:
<disableCleanTables>true</disableCleanTables>
Each unit test automatically rolls back at the end of each table test. You may prevent this as follows:
<disableTestRollback>true</disableTestRollback>
Executing custom statements
Suppose you select to use the restricted schema strategy. Deleting a table might fail should external dependencies exist. The preexec section allows you to execute any custom SQL statements right before a clean takes place in the test cases.
<preexec>
<connections>
<connection>jdbc:mysql://localhost/service</connection>
<driver>com.mysql.jdbc.Driver</driver>
<connectionUsername>root</connectionUsername>
<connectionPassword>abcdefgh</connectionPassword>
<statements>
<statement>truncate serviceconfig</statement>
</statements>
</connections>
</preexec>
You might also wish to execute custom statements after a clean takes place. For this purpose, use the prepopulateDB section:
<prepopulateDB>
<connections>
<connection>jdbc:mysql://localhost/SomeSchema </connection>
<driver>com.mysql.jdbc.Driver</driver>
<connectionUsername>root</connectionUsername>
<connectionPassword>abcdefgh</connectionPassword>
<statements>
<statement>insert into aTable(aTableId) values(1)</statement>
</statements>
</connections>
</prepopulateDB>
Both these options are typically only used in the restricted schema strategy.
Overriding test case factories
Each test case makes a call to a generated data pool factory class to provide an object pre-filled with random data. You may override this random data with anything you want (a constant, a call to a custom method, etc). This is mostly useful for the restricted schema strategy whereby you would typically need to specify all the external dependencies yourself.
<testValues>
<tables>
<table>
<name>yourSchema.Country</name>
<fields>
<name>countryId</name>
<value>1L</value>
</fields>
<fields>
<name>currencyCodeId </name>
<value>com.foobar.getCurrencyCode()</value>
</fields>
</table>
</tables>
</testValues>
Natural Keys
Although considered bad database design by some, the generator is able to deal with tables containing natural keys (that is, tables without a primary key). The generator needs to be told about any natural keys present in a schema in the following manner:
<naturalKeys>
<table name="schemaName.tableName">
<key field="natKey1" />
<key field="natKey2 " />
</table>
</naturalKeys>
This declares table
tableName in schema
schemaName to contain a composite natural key made up of two fields named natKey1 and natKey2.
Generated Values config
Most tables contain a primary key, usually set to a numeric number that auto-increments on each record. Hibernate
supports this behaviour but also supports using a different generator such as a globally-unique identifier generated by the database
or by hibernate itself. You may use the <generatedId> section so as to specify which generator you
wish to use. The following sample illustrates how this may be done:
<generatedId>
<default idpattern="${DB}_id" generator="UUID" />
<map schema="yourschema">
<table name="country" field="country_id" generator="auto" />
<table name="currency" field="currency_id" generator="auto" />
</map>
</generatedId>
This specifies that:
- Field country_id in table country in schema yourschema should have the generated value set to AUTO
- Field currency_id in table currency in schema yourschema should have the generated value set to AUTO
- Any other field matching the pattern databasename_id in any schema and any table will have the generator set to UUID.
The valid generator options so far are: auto, guid, uuid and custom. Custom will use the class defined in
the skeleton template folder (currently calling java.util.UUID.randomUUID()). Please refer to the hibernate documentation for
more details about the other options.
You may specify any fields to ignore in the equality method of each generated class.
Wildcards are acceptable as in other sections of the config.
<equalityExcludes>
<field>*.*.audit_created_by</field>
</equalityExcludes>
- Database design may impose cyclic dependencies on tables through their foreign keys. If these
are set to NOT NULL, the generator will not be able to resolve the dependencies. In order to
resolve this, tables may be tagged as part of the cyclicTableExclusionList. The user needs to define
the table in question, the FK, as well a replacement table to load data from through the Data Pool Factory.
In general, this is rarely necessary and indeed the only way to use the tables
involves temporarily switching off constraints, inserting bootstrap data and
switching on the constraints again.
- You might wish to use the parsing logic of the generator for an external application. For example, a side-project has built an application
that uses a domain specific language to populate a database. Rather than parsing the database, type <enableStateSave>true</enableStateSave>
in the config file and the generator's state will be serialized to disk, ready for use.
- Normally, dao tests are set to rollback at the end of each unit test. Set the option:
<disableTestRollback>true</disableTestRollback> to disable this behaviour.
- Set <enableHibernateValidator> to true to add @NotNull and @Length annotations where appropriate.
- Use the <sessionFactory> configuration to add any custom bean definitions to the sessionFactory bean in spring's configuration file.
- Use the <transactionManagerItems> configuration to add any custom bean definitions to the transactionManager bean in spring's configuration file.
- Use the <additionalContextItems> configuration to add any custom bean definitions to the spring's configuration file.
- Use the <enableJodaSupport> option to use Joda-Time support (use org.joda.time.DateTime in place of java.util.Date).
Have a look at sample.xml for even more options!
Abstract Classes config
Hibernate POJO Generator supports the generation of abstract classes. This feature can be useful when one wishes to auto-generate
a superclass that should never be instantiated. Tagging a table as an abstractTable in the config file will result in its
corresponding auto-generated class to be of type abstract. The following sample illustrates how this may be done:
<abstractTables>
<table>db_name.table1</table>
<table>db_name.table2</table>
<table>db_name.table3</table>
</abstractTables>
This specifies that table1, table2 and table3 will have their corresponding classes generated as abstract. Since abstract classes
cannot be instantiated, the generated DaoFactory will not contain any method referring to the abstract class. Also, the generated
DataPoolFactory cannot create a randomly populated instance of the class. Instead the DataPoolFactory will search through the generated
classes for a valid subclass to our abstract class and instantiate that instead.
Disabling English plurals
Normally, the generator will rename ManyToMany and OneToMany method names for better English-sounding names, for example naming a method getFactories() instead of getFactory().
Setting this option to true will disable this behaviour.
Scripting
In an environment where DB changes are frequent and there exists a need to regenerate a model,
you may wish to streamline your process. You may opt for a process that works like this:
- Using apache, setup a WebDav-enabled folder pointing to somewhere on your server
- Let your Windows/Mac/Linux users mount that folder using My Network Places or whichever mechanism your OS supports
- On the server, you setup an inotify watch waiting on that webdav folder.
- Run a script to wake up when inotify tells it to, run the generator and deploy your output via Maven or some other mechanism.
- Your clients need merely drag the Hibernate Pojo Generator's config file to the WebDav folder for a new model to be generated and deployed.
Since it uses the inotify mechanism, it will not consume
any resources until someone actually copies over a file. Using
Maven, your clients' IDE will automatically download the new model on the next
build (if they set the version to SNAPSHOT) or manually (if they set the generators' config file to deploy a release artifact instead).
You will need:
Note that this script is currently pointing to
Archiva as our Maven repository store and fetches the generator executable from the latest build obtained from
CruiseControl.
Controlling cascading
By default, the synchronizer generates code in a way that all one-to-many, many-to-one, many-to-many and one-to-one will have
the appropriate annotations so as to make Hibernate cascade saves; such as automatically saving all
child tables linked to a parent table.
This section allows you to enable/disable cascading.
Set the default for each category (one-to-many, many-to-one, etc). Then override any properties
by using the <except> tags. Wildcards ("*") are accepted in a limited way.
Examples:
<cascading>
<one-to-many default="true">
<except package="*" class="yourclass" property="*" />
</one-to-many>
</cascading>
For one-to-many entries, in any package, and class named "yourclass" and any property contained
in it, don't add Cascade=All.
<except package="util" class="*" property="*" />
Any property of any class in package util will/will not (depending on default) have Cascade=All
suppressed.
Notes: Do not give the full package name in the "package" section. If your schema in the db is named
"some_schema" and the resultant code is placed as "someSchema/someClass" you would put in "someSchema"
only and not something like: com.yourcompany.someSchema.
Controlling Fetch Type
By default, the synchronizer generates code in a way that all one-to-many, many-to-one, many-to-many and one-to-one will have
the appropriate annotations so as to make Hibernate behave in a lazy fashion (by loading data only when a collection is
accessed).
This section allows you to control this behaviour.
Set the default for each category (one-to-many, many-to-one, etc). Then override any properties
by using the <except> tags. Wildcards ("*") are accepted in a limited way.
Examples:
<fetchtype>
<one-to-many defaultlazy="true">
<except package="*" class="yourclass" property="*" />
</one-to-many>
</fetchtype>
For one-to-many entries, in any package, and class named "yourclass" and any property contained
in it, don't add Cascade=All.
<except package="util" class="*" property="*" />
Any property of any class in package util will/will not (depending on default) have Cascade=All
suppressed.
Notes: Do not give the full package name in the "package" section. If your schema in the db is named
"some_schema" and the resultant code is placed as "someSchema/someClass" you would put in "someSchema"
only and not something like: com.yourcompany.someSchema.
Disabling Underscore conversions
Normally, table and schema names will be converted to suitable Java conventions for example underscore_schema.underscore_table is changed to userscoreSchema.userscoreTable.
Setting this option to true disables this behaviour.
Multiple Schema Support
Hibernate Pojo Generator provides full support for handling multiple schemas, that is, tables linked by foreign keys to other tables which are not in the same schema.
Schema Strategy
The schema strategy configuration parameter controls how the generator is to behave in the presence of multiple schemas. There are 4 settings you may use:
Restricted
In this mode, the generator starts off from the database catalog you specify (the databaseCatalog configuration setting). Whenever it encounters a link to an external schema, it will not follow it and leave the field set to the field type equivalent. For example if you have the following schema with the Order table being in a different schema to the Item table:
Order Table
OrderId - Integer
DateOfOrder - Date
Item Table
ItemId - Integer
OrderId - Integer
Description - VarChar(200)
The generated code for the Item table, Item.java, will have:
private Integer orderId;
Under this mode, it will therefore not be possible to call Item.getOrders(). Of course, if the order table is moved to the same schema as the Item table, the code generator changes to:
private Order order;
Use this mode whenever you want to completely isolate your code from accessing external schemas. Note that using this strategy will mean you will need to take care of all external links yourself as cascading across schemas will not be possible. For the same reason, should you wish to make use of the generated test case code, you will need to provide additional configuration details for each external link.
Partial
This mode relaxes the restricted mode condition of not following external referenced schemas - code is also generated for the external schema tables referenced by your main schema. However the generator will only generate external schema code directly referenced by your main catalog.
Use this option if you want to give your developers all the objects necessary to access their own schema together with a minimal set of objects from any other referenced schema.
Full
This mode is similar to the partial schema strategy described above, differing only in the number of tables imported when an external referenced schema is encountered. While the partial strategy imports only those tables directly referenced by the primary schema, the full schema strategy will import all the tables of the schema that are referenced from the main schema.
Use this option whenever you want to give your developers all objects of all schemas related to the project.
All
In this strategy, the databaseCatalog configuration setting is ignored and code is generated for all schemas present in the specified database.
This option is useful if you want to generate a central repository of all the classes required to access all the available database schemas.