OGB is a builder for an arbitrary graph of beans that follow the JavaBean convention, its useful for creating test data for example.
Let's say that the following classes belong into your domain model:
With OGB building a Company with three employees is an easy as
Here is what's happening behind the scenes:
- the builder will try to match a node name into a Class, using a default ClassNameResolver strategy that requires a package name.
- then an instance of said class must be created, using a default NewInstanceResolver strategy that calls a no-args constructor.
- the parent/child relationship must be resolved for nested nodes, here it gets a little tricky as two other strategies come into play. RelationNameResolver will yield the name of the child property in the parent, and the name of the parent property in the child (if any, in this case, Employee has a parent property aptly named 'company'). ChildPropertySetter will 'insert' the child into the parent taking into account if the child belongs to a Collection or not (in this case employees should be a list of Employee instances in Company).
All 4 strategies have a default implementation that work as expected if the code follows the usual conventions for writing JavaBeans. But if by any chance any of your beans do not follow the convention you may plug your own implementation of each strategy. Each startegy setter is Closure friendly, for example
OGB supports ids per node as SwingBuilder does, meaning that you can 'store' a reference to a node in the builder, this is useful to relate one instance with many others as well. Because a property named 'id' may be of business meaning in some domain models OGB has a strategy named IdentifierResolver that you may configure to change the default name value ('id'). The same may happen with the property used for referencing a previously saved instance, a strategy named ReferenceResolver will yield the appropriate value (default is 'refId'):
Its worth mentioning that you can not modify the properties of a referenced bean.
For those rare occasions where OGB can't locate your classes (it happens when you run a script using groovyConsole) you may define a classLoader for OGB to resolve classes. Try for example running the following script inside groovyConsole and then comment out the classLoader property.