-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathsample.xml
executable file
·1029 lines (870 loc) · 46.5 KB
/
sample.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="iso-8859-1"?>
<appconfig>
<!-- Valid recognised options so far: MYSQL, MSSQL (and untested: PostgreSQL). Unknown options will be treated as "MySQL". You may
pass 'dialect' as an attribute to override the hibernate dialect class name eg dbType dialect="com.foo.bar.PgsqlCustomDialect" -->
<dbType>MYSQL</dbType>
<!-- Which jdbc driver to use. Make sure the jar driver is in the classpath -->
<driver>com.mysql.jdbc.Driver</driver>
<!-- This is used to determine the JDBC connection string to use -->
<jdbcConnectionString>
jdbc:mysql://127.0.0.1/util
</jdbcConnectionString>
<!-- Database location (this ends in applicationContext.xml) -->
<databaseIP>localhost</databaseIP>
<!-- Database name -->
<databaseCatalog>hbnPojoTest</databaseCatalog>
<!-- Schema name (pgsql only.) Default: public -->
<databaseSchema>public</databaseSchema>
<!-- Username with access to view meta data -->
<databaseUsername>root</databaseUsername>
<!-- Password for the given username -->
<databasePassword>abcdefgh</databasePassword>
<!-- Target where source files are to be written (overwriting files on name conflicts!) -->
<sourceTarget>D:/yourcompany</sourceTarget>
<!-- Specify the subfolder, relative to "sourceTarget", where support jars such as hibernate.jar are to
be placed -->
<libPath>libs</libPath>
<!-- Name of project. Package names might be named <toplevel>.<projectName>
This is also used to calculate the serializationUID key. -->
<projectName>sams</projectName>
<!-- Toplevel package name -->
<topLevel>com.yourcompany</topLevel>
<!-- Schema strategy options:
RESTRICT: Restrict to given schema - links to foreign schemas will be left as "Long", "integer", etc.
PARTIAL: Import given schema + as little as possible from other schemas
FULL: Import given schema + complete schemas of any FK links from the given schema)
ALL: Fetch all schemas in the DB, regardless of which one is specified by <databaseCatalog>
-->
<schemaStrategy>PARTIAL</schemaStrategy>
<!-- EVERYTHING beneath this line is OPTIONAL -->
<!-- Enable this to use Joda dateTime instead of java.util.Date -->
<enableJodaSupport>false</enableJodaSupport>
<!-- Enable this to use Jadira @Types instead of java.util.Date -->
<enableJadiraSupport>false</enableJadiraSupport>
<!-- Enable this to add annotations useful for serializing to JSON. ManagedReference determines @JsonManagedReference/@JsonBackReference -->
<enableJacksonSupport managedReference="false">false</enableJacksonSupport>
<!-- If enableJodaSupport is false and enableJDK8Support is true, we use java.util.LocalDate -->
<enableJDK8Support>false</enableJDK8Support>
<!-- If not disabled, generates a spring context containing mock objects for each repository
for testing. Use the name tag to define the context filename. Default: true and filename set to beans.test.mockito.xml -->
<enableMockitoBeans filename="some.file.name.xml">true</enableMockitoBeans>
<!-- If not disabled, generates some helper classes -->
<enableUtilsBeans>true</enableUtilsBeans>
<!-- Enable this to add @NotNull and @Length annotations where appropriate.
Requires hibernate validator jar to be in your classpath. -->
<enableHibernateValidator>false</enableHibernateValidator>
<!-- Default folder name under sourceTarget. Default is "src" (or src/main/java if maven is enabled) -->
<sourceFolderName>src/main/java</sourceFolderName>
<!-- Default folder name for test unit under sourceTarget.
Default is "test/unit" or (src/test/java if maven is enabled). daoCustomContextConfig is optional and if defined will use
whatever you type instead of the non-spring boot way of loading a context in tests -->
<testFolderName daoCustomContextConfig="@SpringApplicationConfiguration(classes = Application.class)">src/test/java</testFolderName>
<!-- Only used to store state, normally more relevant for your application. -->
<resourceFolder>src/main/resources</resourceFolder>
<!-- Used to store log4j.properties. -->
<testResourceFolder>src/test/resources</testResourceFolder>
<!-- Target name for spring context file. -->
<applicationContextFilename disableGeneration="false">applicationContext.xml</applicationContextFilename>
<!-- Any custom entries to insert in the sessionFactory bean definition of
the generated application context. Useful when you add interceptors and so on.
Eg: <property name="entityInterceptor">
<bean class="com.foo.persistence.impl.UUIDInterceptor" />
</property>
-->
<sessionFactory><![CDATA[]]></sessionFactory>
<!-- Any custom entries to insert in the transactionManager bean definition of
the generated application context.
-->
<transactionManagerItems><![CDATA[]]></transactionManagerItems>
<!-- Any custom entries to insert in spring's context file
-->
<additionalContextItems><![CDATA[]]></additionalContextItems>
<!-- Select the connection pool to use. Valid options are: C3P0, BoneCP, HikariCP, JNDI. Set useLDAP to true if you want
LDAP support. Set useLDAPImport if you plan on doing a spring import instead of wanting the appropriate beans being generated.
enableDynamicLdapDataSource set to true will bounce the datasource off DynamicDataSourceProxy too. Other ldap properties are
optional for non-ldap configs. -->
<connectionPool enableDynamicLdapDataSource="true"
useLDAP="false"
useLDAPImport="false"
ldapServer="ldap://10.239.32.63:10389"
ldapBase="dc=dev,dc=foo,dc=com"
ldapCn="cn=YOUR-CN-HERE">C3P0</connectionPool>
<!-- Define the location of all the objects. map schema="default" will be used whenever there's no definition
set. You can leave out the default section too, it will be filled in programatically.
You may use ${XXX} to refer to any other property in this file. ${DB} has special meaning: it will be replaced
by the schema under processing. -->
<dbPackageMap>
<map schema="DEFAULT">
<!-- Location of hibernate objects.
${DB} will be replaced by the schema under operation dynamically. -->
<objectPackage>
${topLevel}.${projectName}.model.obj.${DB}
</objectPackage>
<objectInterfacePackage skip="true">
${topLevel}.${projectName}.model.obj.${DB}.iface
</objectInterfacePackage>
<!-- Location of repository objects (spring data only) -->
<objectTableRepoPackage>
${topLevel}.${projectName}.model.obj.${DB}.repository
</objectTableRepoPackage>
<!-- Location of repository factory objects. -->
<repositoryFactoryPackage>
${topLevel}.${projectName}.model.obj.${DB}.repository.factory
</repositoryFactoryPackage>
<!-- Location of hibernate DAO objects. -->
<daoPackage>
${topLevel}.${projectName}.model.dao.${DB}
</daoPackage>
<!-- Location of hibernate DAO Implementation objects. -->
<daoImplPackage>
${topLevel}.${projectName}.model.dao.${DB}.impl
</daoImplPackage>
<!-- Location of hibernate enum objects. -->
<enumPackage targetbase="/some/other/path">
${topLevel}.${projectName}.enums.db.${DB}
</enumPackage>
<!-- Location of class subtype enum objects. -->
<enumSubtypePackage>
${topLevel}.${projectName}.enums.subtype.${DB}
</enumSubtypePackage>
<!-- Location of hibernate factory objects. -->
<factoryPackage>
${topLevel}.${projectName}.factories.${DB}
</factoryPackage>
<!-- Location of repository factory objects. -->
<repositoryFactoryPackage>
${topLevel}.${projectName}.factories.${DB}
</repositoryFactoryPackage>
<!-- Location of assorted classes -->
<utilPackage>
${topLevel}.${projectName}.util
</utilPackage>
<!-- Location of data layer objects. -->
<dataPackage>
${topLevel}.${projectName}.services.data
</dataPackage>
</map>
<map schema="yourschema">
<objectInterfacePackage>${topLevel}.yourschema.model.iface</objectInterfacePackage>
<objectPackage>${topLevel}.yourschema.model</objectPackage>
<daoPackage>${topLevel}.yourschema.model.dao</daoPackage>
<enumPackage>${topLevel}.yourschema.enums.db</enumPackage>
<daoImplPackage>${topLevel}.yourschema.model.dao.impl</daoImplPackage>
<enumSubtypePackage>
${topLevel}.yourschema.enums.subtype
</enumSubtypePackage>
<factoryPackage>
${topLevel}.yourschema.factories
</factoryPackage>
<dataPackage>
${topLevel}.yourschema.services.data
</dataPackage>
</map>
</dbPackageMap>
<!-- Enable/disable the generation of enums for class subtypes. These enums allow you to perform
a switch..case on the parent object handle eg switch(someObj.getSubclassType()) {...}. Default=generate enums. -->
<disableSubtypeEnumGeneration>false</disableSubtypeEnumGeneration>
<!-- Use the coalesceEnums section to specify enums that are shared across multiple tables in order
to collapse them into one enum defintion -->
<!--
<coalesceEnums>
<schema name="yourschema">
<enum name="DaysOfWeek">
<field>delivery.deliveryDay</field>
<field>weather.dayOfWeather</field>
</enum>
</schema>
</coalesceEnums>
-->
<!-- Property renaming. Use the inverseName for cases where you have
ManyToOne and you want to rename the OneToMany end too. -->
<renaming>
<schema name="yourschema">
<field srcName="tablename.fieldName" dstName="someFieldName" inverseName="Foo" />
</schema>
</renaming>
<!-- 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.
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 treatLinkAsEnum configuration setting.
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.
-->
<!--
<treatLinkAsEnum>
<schema name="yourschema">
<field src="tablename.fieldName" dstTable="tableContainingEnums" keyColumnName="someColName" valueColumnName="someValColumn" otherColumnNames="description,foo_bar" />
</schema>
</treatLinkAsEnum>
-->
<!-- If this is set to true, the state of all generated objects is serialized to disk
and the relevant hibernate generator class files are copied over to the target folder. This
allows for integration with other tools. -->
<enableStateSave>true</enableStateSave>
<!-- If enabled, we add @Builder support for generated models. -->
<enableLombokBuilderPattern>true</enableLombokBuilderPattern>
<!-- If enabled, we make use of spring jpa instead of our custom code.
pass in factoryClass="com.some.factory.class.BeanName" as an attribute if you wish to
override the default spring factory.
Pass in repoInterface to override the default Spring repo interface from
org.springframework.data.jpa.repository.JpaRepository to something else. Eg:
repoInterface="com.my.CustomRepository"
-->
<enableSpringData writeFiles="false" factoryClass="com.som.factory.class.BeanName">true</enableSpringData>
<!-- If true, the resultant unit test will not contain code to delete all the tables prior to each test -->
<disableCleanTables>true</disableCleanTables>
<!-- If true, the generator will make no attempt at pluralizing ManyToMany/OneToMany method names
e.g. normally getFactory() will be named getFactories(). -->
<disableEnglishPlural>false</disableEnglishPlural>
<!-- Additional rules to pass to the pluralization rule engine. -->
<!-- The following sample rule makes getTransactionMO become getTransactionMOs
instead of getTransactionMOes -->
<!--
<customPluralization>
<rule regexmatch="(?i)(.*)MO" regexreplace="$1MOs" />
</customPluralization>
-->
<!-- Normally, table and schema names will be converted to better Java representations e.g.
underscore_schema.underscore_table will become userscoreSchema.userscoreTable. Set this option to true
to disable this behaviour -->
<disableUnderscoreConversion>false</disableUnderscoreConversion>
<!-- Normally, dao tests are set to rollback at the end of each unit test. Set this option to true
to disable this behaviour -->
<disableTestRollback>false</disableTestRollback>
<!-- OneToOne db mappings cannot be automatically determined simply by looking at the metadata. Use the
oneToOne section to list the fields in each table that should be treated as OneToOne links -->
<oneToOne>
<table name="someschema.sometable" field="someFieldName" />
</oneToOne>
<!--
List of tables/fields that should be skipped. You'll have to handle any table links yourself.
Use *.tablename to skip that table for all schemas. yourschema.* skips all tables in yourschema.
Use <everything-except> to signal "ignore all tables/fields except the ones
listed". You may also add "except-for" to the field ignore list to mean: ignore all those
fields except for the ones matching schema.tablename (wildcards accepted, CSV for multiple values)
-->
<!--
<ignore>
<table>*.somekindoftable</table>
<field>someschema.sometable.somefieldname</field>
<field except-for="*.sometable,someschema.sometable">someschema.sometable.somefieldname</field>
<everything-except>
<table>*.atable</table
</everything-except>
</ignore>
-->
<!--
Setup your custom annotations using the <annotations> section
classname eg: mycompany.Foo (don't use com.xon.mycompany.Foo, just use
the schemaname in camelcase without underscores followed by your classname).
You may also use wildcards in the classname definition eg *.yourclass, yourschema.* or *.*
The symbol in <extends> section: "!", if present, will be replaced with the PK type of the class eg BaseEntity<!> will become BaseEntity<Long> or BaseEntity<Integer> as appropriate
-->
<!--
<annotations>
<class name="yourPackage.yourClass">
<imports>
<import>your.custom.import</import>
<import>your.custom.import2</import>
</imports>
<implements>
<interface>someInterface</interface>
<interface>someOtherInterface</interface>
</implements>
<extends>
<extend>someClass</extend>
</extends>
<classAnnotation>
<![CDATA[
@yourcustomAnnotation
]]>
</classAnnotation>
<customClassCode>
<![CDATA[ extra custom class code pasted at the end]]>
</customClassCode>
<customClassCodeFields>
<![CDATA[ extra custom class code pasted at the start of the field list]]>
</customClassCodeFields>
Always use the singular tense to use amount and not amounts even if it appears in plural form in the resulting code
<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>
-->
<!--
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.
-->
<!--
<linktables>
<table name="yourcatalog.UserBillingMap">
<link srcField="userId" dstField="billingId" />
</table>
</linktables>
-->
<!-- Use this section to override the generator to use for your primary keys. Normally "AUTO" is what
you need for auto-incrementing primary keys but other valid options for the generator are GUID, UUID,
CUSTOM and IDAWARE. CUSTOM will use CustomGeneratedId class found in the skeleton directory. IDAWARE uses
the IdPresentAwareGenerator class found in the skeleton directory and behaves like AUTO except that
if you set an ID of a class, it will use that rather than ignoring the value and
fetching a new one from the DB. -->
<!--
<generatedId>
<default idpattern="${DB}_id" generator="AUTO" />
<map schema="yourschema">
<table name="country" field="currency_code"
generator="UUID" />
<table name="currency_country" field="currency_country_id"
generator="CUSTOM" />
</map>
</generatedId>
-->
<!--
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>
-->
<!--
Use this section to flag the fields of those tables that do not contain a primary key
and instead rely on natural keys. Normally this is bad database design but you might need to deal
with certain legacy databases. For composite natural keys, list multiple key entries under the same
table section
-->
<!--
<naturalKeys>
<table name="hbnPojoTest.NaturalKeyParent">
<key field="natKeyId" />
</table>
<table name="hbnPojoTest.NatKeyCompositeParent">
<key field="natKeyCompParentId" />
<key field="secondId" />
</table>
</naturalKeys>
-->
<!-- 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/yourschema</connection>
<driver>com.mysql.jdbc.Driver</driver>
<connectionUsername>root</connectionUsername>
<connectionPassword>abcdefgh</connectionPassword>
<statements>
<statement>truncate yourtable</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>
-->
<!-- 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.
If target is set, system will use the given datapool instead.
-->
<!--
<testValues>
<target schema="util" datapool="com.foo" />
<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>
-->
<!-- Tagging a table as immutable will make hibernate skip dirty checking etc.
Wildcards are supported. The optional generate-static-test="true" indicates
that the table/s in question should result in the datapool factory creating
static random objects instead of reading items off the database. -->
<immutableTables>
<table generate-static-test="false">someschema.*</table>
</immutableTables>
<!-- Tagging a table as abstract will result in its corresponding auto-generated class to be
of type abstract. -->
<abstractTables>
<table>db_name.table_name</table>
</abstractTables>
<!-- Database design may impose cyclic dependencies on tables through their foreign keys. If these
are set to NOT NULL, the POJO 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
-->
<cyclicTableExclusionList>
<table name="someschema.sometable" field="someFieldName" replacement="someschema.sometable" />
</cyclicTableExclusionList>
<!-- 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) -->
<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>
<!-- Use the disableForwardLinks section to specify that the generator
should not generate the OneToMany side in the case of one-to-many/many-to-one links.
* wildcards are allowed implying "any" (see examples) -->
<disableForwardLinks>
<noforwardlink from="schemaA.*" to="schemaB.*" from-field="*" />
<noforwardlink from="*.*" to="*.country" from-field="*" />
<noforwardlink from="schemaA.sometable" to="schemaB.linkedtable" from-field="somefield" />
</disableForwardLinks>
<!-- In rare cases you might wish to instruct the generator
to leave a FK as an integer (that is, don't follow the object just
as in the restrict case across multiple schemas. The following
achieves this. The defined names are table-centric eg: "country_foo" not "CountryFoo"
You probably will also need to set the testValues option to allow for proper
datapoolfactory generation.
-->
<noFollowLinks>
<nofollow from="schemaA.*" to="schemaB.*" from-field="*" />
<nofollow from="*.*" to="*.country" from-field="*" />
<nofollow from="schemaA.sometable" to="schemaB.someOtherTable" from-field="somefield" />
</noFollowLinks>
<!-- You can opt to remove foreign keys in the DB but force the generator to pretend they're
still there. This is not usually recommended and is only supported for high performance reasons. Pattern is a regex expression
so .*_id will match foo_id, bar_id, etc. Replace can use $n for capturing groups as per Java string replace method. -->
<fakeFK enabled="true" pattern="(.*)_id" replacePattern="$1">
<except table="someschema.sometable" enabled="false" pattern="" replacePattern="" />
</fakeFK>
<!-- Use the unique fields section to specify the fields that are marked as unique
in the database. Fields you specify here will make the datapool factory attempt
to generate unique random values to reduce the possibility of a database duplicate key
collision. This is basically only useful for unit testing and has no effect on the actual
model -->
<uniqueKeys>
<unique schema="schemaA" table="tablename" field="fieldname" />
</uniqueKeys>
<!-- Spring version to target. Recognised options are 2 and 3. Default: 2 -->
<springVersion>3</springVersion>
<!-- This section specifies that, though everything should be processed
as usual, no files for the schemas listed below should be generated. This
is useful in the case where some schemas are to be imported in a 3rd party
fashion (especially useful in conjunction with <disableBackLinks>) -->
<noOutputForSchema>
<ignore>someSchema</ignore>
<!-- whitelist instead. -->
<ignoreAllExcept>someSchema1</ignoreAllExcept>
<ignoreAllExcept>someSchema2</ignoreAllExcept>
</noOutputForSchema>
<!-- 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. You
may also use to-package as exceptions
Examples:
1.
<one-to-many default="true">
<except package="*" class="yourclass" property="*" />
</one-to-many>
For one-to-many entries, in any package, and class named "yourclass" and any property contained
in it, don't add Cascade=All.
2. <except package="util" class="*" property="*" />
Any property of any class in package util will/will not (depending on default) have Cascade=All
suppressed.
3. <except-to to-package="util" to-class="*" to-property="*" />
Any property pointing to schema util will be 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.
-->
<cascading>
<one-to-many default="true" defaultCascade="SAVE_UPDATE">
<except package="yourpackage" class="yourclass" property="yourproperty" />
<except package="*" class="yourclass" property="yourproperty" cascade="LOCK" enabled="true"/>
<except package="yourpackage2" class="yourclass2" property="yourproperty2" />
</one-to-many>
<many-to-one default="true">
<except package="yourpackage" class="yourclass" property="yourproperty" />
</many-to-one>
<many-to-many default="true">
<except package="yourpackage" class="yourclass" property="yourproperty" />
</many-to-many>
<one-to-one default="true">
<except package="yourpackage" class="yourclass" property="yourproperty" />
</one-to-one>
</cascading>
<!-- Override fetchtype of N-to-M (lazy or eager fetching) -->
<fetchtype>
<one-to-many defaultlazy="true">
<except package="yourpackage" class="yourclass" property="yourproperty" />
</one-to-many>
<many-to-one defaultlazy="true">
<except package="yourpackage" class="yourclass" property="yourproperty" />
</many-to-one>
<many-to-many defaultlazy="true">
<except package="yourpackage" class="yourclass" property="yourproperty" />
</many-to-many>
<one-to-one defaultlazy="true">
<except package="yourpackage" class="yourclass" property="yourproperty" />
</one-to-one>
</fetchtype>
<!-- Specify any fields to ignore in the equality method of each generated
class. -->
<equalityExcludes>
<field>*.*.audit_created_by</field>
</equalityExcludes>
<!-- Specify any fields to ignore in the toString method of each generated
class. -->
<toStringExcludes>
<field>*.*.audit_created_by</field>
</toStringExcludes>
<!-- Specify any fields to mark as being transient. Transient fields
aren't saved and are ignored in tests. This is useful for marking
up fields that are derived in the DB eg by means of a stored procedure
or trigger. Wildcards are accepted. -->
<transientFields>
<field>schema.table.field</field>
<field>*.table.field</field>
</transientFields>
<!-- Specify any fields to use a Money type (JSR354, javamoney). Fields listed here should also have a matching XXX_currency field
to store the currency. typeOverride is optional and if defined
will use the type you give it instead of the jadira ones (meant for bug workaround only)
-->
<moneyFields typeOverride="com.your.custom.override.classType">
<field>schema.table.field</field>
<field>*.table.field</field>
</moneyFields>
<!-- Specify any fields to use a CurrencyUnit type (JSR354, javamoney). typeOverride is optional and if defined
will use the type you give it instead of the jadira ones (meant for bug workaround only)
-->
<currencyUnitFields typeOverride="com.your.custom.override.classType">
<field>schema.table.field</field>
<field>*.table.field</field>
</currencyUnitFields>
<!-- Uses Jasypt to encrypt/decrypt string fields.
See: http://tomaszdziurko.pl/2013/07/transparently-persist-retrieve-encrypted-data-database/
Requires jaspyt hibernate library : org.jasypt:jasypt-hibernate4:1.9.2
You may also add "except-for" to the field ignore list to mean: ignore all those
fields except for the ones matching schema.tablename (wildcards accepted, CSV for multiple values)
NB: Security standards establish that two different encryption operations on the same data should not
return the same value (due to the use of a random salt). Because of this, none of the fields that are set to be
encrypted when persisted can be a part of a WHERE clause in your search queries for the entity they belong to.
-->
<encryptedFields>
<field>schema.table.field</field>
<field>*.table.field</field>
<field except-for="*.sometable,someschema.sometable">someschema.sometable.somefieldname</field>
</encryptedFields>
<!-- Enable support for writing out schema .yaml files for including in an openapi spec. If externalIdSchema is set, then
IDs will refer to an external schema so as to allow alternate mappings eg encrypted IDs. Common dir is used to set
where internal references can be found eg "./openapi-common" which contains a file called Common.yaml which contains page schemas
If delegateOutputDir is set, we also generate some delegates intended for use with an openapi generator (will not overwrite existing classes)
if testForAsciiDocPackage is set, we also generate a skeleton to invoke a test per table to make asciidoc calls. The code assumes an abstract class to inherit from. Here's a reference implementation
@TestPropertySource(properties = {
"spring.flyway.enabled = false",
"spring.jpa.hibernate.ddl-auto = create",
"spring.jpa.database = HSQL",
"spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.HSQLDialect",
"spring.datasource.driverClassName = org.hsqldb.jdbcDriver",
"spring.datasource.url = jdbc:hsqldb:mem:crud_demo",
"spring.datasource.username = sa",
"spring.datasource.password =",
"spring.jpa.properties.hibernate.default_schema = ",
"spring.endpoints.actuator.enabled=false",
"spring.cache.type=NONE"
})
@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.HSQL)
@FixMethodOrder
@SpringBootTest
@AutoConfigureMockMvc(addFilters = true)
@AutoConfigureRestDocs(outputDir = "build/generated-snippets", uriHost = "api.domain.com", uriPort = 443)
public abstract class AbstractGenericTest {
@Getter @Autowired
protected MockMvc mockMvc;
@Autowired
EntityIdUtils entityIdUtils;
@Autowired
protected ObjectMapper objectMapper;
@Autowired
private WebApplicationContext context;
protected ResultActions executePostCall(String url, String request, String documentTitle, RequestFieldsSnippet requestFieldsSnippet) throws Exception{
return getMockMvc().perform(
RestDocumentationRequestBuilders.post(url)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(request)
)
.andDo(document(documentTitle,
requestFieldsSnippet))
.andDo(MockMvcResultHandlers.print());
}
protected ResultActions executeGetCall(String url, Object[] urlVars, String documentTitle, ResponseFieldsSnippet responseFieldsSnippet, PathParametersSnippet pathParametersSnippet) throws Exception{
ResultActions resultActions = getMockMvc().perform(
RestDocumentationRequestBuilders.get(url, urlVars)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
)
.andDo(MockMvcResultHandlers.print());
if (pathParametersSnippet == null) {
resultActions.andDo(document(documentTitle, responseFieldsSnippet));
}else{
resultActions.andDo(document(documentTitle, pathParametersSnippet, responseFieldsSnippet));
}
return resultActions;
}
protected ResultActions executePutCall(String url, Object[] urlVars, String request, String documentTitle, PathParametersSnippet pathParametersSnippet) throws Exception{
return getMockMvc().perform(
RestDocumentationRequestBuilders.put(url, urlVars)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(request)
)
.andDo(document(documentTitle, pathParametersSnippet))
.andDo(MockMvcResultHandlers.print());
}
protected ResultActions executeDeleteCall(String url, Object[] urlVars, String documentTitle, PathParametersSnippet pathParametersSnippet) throws Exception{
return getMockMvc().perform(
RestDocumentationRequestBuilders.delete(url, urlVars)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
)
.andDo(document(documentTitle, pathParametersSnippet))
.andDo(MockMvcResultHandlers.print());
}
protected FieldDescriptor[] createStandardDtoFieldDescriptors(String name){
return createStandardDtoFieldDescriptors(name, false);
}
protected FieldDescriptor[] createStandardDtoFieldDescriptors(String name, boolean delete){
FieldDescriptor[] tempFieldDescriptors = {
fieldWithPath("id").description("ID of " + name),
fieldWithPath("createdAt").description("The Date/time the " + name + " was created"),
fieldWithPath("updatedAt").description("The Date/time the " + name + " was last updated"),
};
List<FieldDescriptor> fieldDescriptors = Arrays.asList(tempFieldDescriptors);
if (delete){
fieldDescriptors.add(fieldWithPath("deletedAt").description("The Date/time the " + name + " was deleted"));
}
return fieldDescriptors.toArray(new FieldDescriptor[0]);
}
protected FieldDescriptor[]
standardListFieldDescriptors = {
fieldWithPath("pageable").description("The request is pageable"),
fieldWithPath("pageable.sort").description("Sorting options"),
fieldWithPath("pageable.sort.empty").ignored(),
fieldWithPath("pageable.sort.sorted").description("The content is sorted"),
fieldWithPath("pageable.sort.unsorted").description("The content is unsorted"),
fieldWithPath("pageable.offset").description("The current offset of results"),
fieldWithPath("pageable.pageSize").description("The size of each page"),
fieldWithPath("pageable.pageNumber").description("The current page number"),
fieldWithPath("pageable.paged").description("The response has been paged."),
fieldWithPath("pageable.unpaged").description("The response has not been paged"),
fieldWithPath("sort").description("Sorting options"),
fieldWithPath("sort.sorted").description("The content is sorted"),
fieldWithPath("sort.empty").ignored(),
fieldWithPath("empty").ignored(),
fieldWithPath("sort.unsorted").description("The content is unsorted"),
fieldWithPath("first").description("Whether the current page is the first page"),
fieldWithPath("last").description("Whether the current page is the last page"),
fieldWithPath("totalPages").description("Total number of response pages"),
fieldWithPath("totalElements").description("Total number of items in the response"),
fieldWithPath("size").description("The size of each page"),
fieldWithPath("number").description("The current page number"),
fieldWithPath("numberOfElements").description("The number of items in the current page"),
};
protected RestDocumentationResultHandler getDefaultDocs() {
return getDefaultDocs("{methodName}");
}
protected RestDocumentationResultHandler getDefaultDocs(String title) {
return document(title,
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint()));
}
protected static class ConstrainedFields {
protected final ConstraintDescriptions constraintDescriptions;
public ConstrainedFields(Class<?> input) {
this.constraintDescriptions = new ConstraintDescriptions(input);
}
public FieldDescriptor withPath(String path) {
return fieldWithPath(path).attributes(key("constraints").value(StringUtils
.collectionToDelimitedString(this.constraintDescriptions
.descriptionsForProperty(path), ". ")));
}
}
public ResultActions retrieve(String url, Long userId, Class<?> responseDtoClass, String documentTitle, ResponseFieldsSnippet responseFieldsSnippet) throws Exception {
return retrieve(url, userId, responseDtoClass, documentTitle, responseFieldsSnippet, null);
}
public ResultActions retrieve(String url, Long userId, Class<?> responseDtoClass, String documentTitle, ResponseFieldsSnippet responseFieldsSnippet, PathParametersSnippet pathParametersSnippet) throws Exception{
String encryptedUserId = entityIdUtils.encrypt(EntityId.of(userId));
ResultActions resultActions = executeGetCall(url, new String[]{encryptedUserId}, documentTitle, responseFieldsSnippet, pathParametersSnippet)
.andExpect(status().isOk());
MvcResult mvcResult = resultActions.andReturn();
HashMap<?, ?> response = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), HashMap.class);
if (response.get("id") != null){
assertEquals((String)entityIdUtils.decrypt(encryptedUserId), entityIdUtils.decrypt((String)response.get("id").toString()));
} else if (response.get("content") != null){
// assertEquals(entityIdUtils.decrypt(encryptedUserId, String.class), entityIdUtils.decrypt(((List<HashMap<String, String>>)(response.get("content"))).get(0).get("id").toString(), String.class));
}
return resultActions;
}
public void retrieveList(String url, int totalElements, String documentTitle, ResponseFieldsSnippet responseFieldsSnippet) throws Exception {
retrieveList(url, totalElements, documentTitle, responseFieldsSnippet, null);
}
public void retrieveList(String url, int totalElements, String documentTitle, ResponseFieldsSnippet responseFieldsSnippet, PathParametersSnippet pathParametersSnippet) throws Exception{
executeGetCall(url, new String[]{}, documentTitle, responseFieldsSnippet, pathParametersSnippet)
.andExpect(status().isOk())
.andExpect(jsonPath("totalElements").value(totalElements))
;
}
@SuppressWarnings("all")
public <T extends JpaRepository> void createNew(String url, String requestToSend, T baseService, String documentTitle, RequestFieldsSnippet requestFieldsSnippet) throws Exception {
MvcResult mvcResult = executePostCall(url, requestToSend, documentTitle, requestFieldsSnippet)
.andExpect(status().isCreated())
.andExpect(redirectedUrlPattern("**" + url + "*"))
.andReturn();
String id = mvcResult.getResponse().getRedirectedUrl().substring(mvcResult.getResponse().getRedirectedUrl().lastIndexOf("/") + 1);
Long userId = EntityId.of((String)entityIdUtils.decrypt(id)).toLong();
BaseObject entity = (BaseObject)baseService.getOne(userId);
assertTrue("The new item was not inserted in the database.", entity != null);
assertEquals(userId, entity.getId());
}
}
-->
<openApi enabled="true" asciiDocTemplateDir="some/output/dir" commonPackage="com.toplevel.common" outputDir="openapi-schemas" testForAsciiDocPackage="com.foo.bar.generated" testForAsciiDocDir="../src/main/java/" delegateOutputDir="delegates" externalIdSchema="./EntityId.yaml#/EntityId" commonDir="./some/path/" >
<writeOnlyField>schema.table.field</writeOnlyField>
<readOnlyField>schema.table.field</readOnlyField>
</openApi>
<!-- Custom type override -->
<customTypes>
<field type="java.util.Currency">schema.table.field</field>
</customTypes>
<!-- 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) -->
<disableBackLinksInDataPoolFactory>false</disableBackLinksInDataPoolFactory>
<!-- If true, don't write the datapool factory classes -->
<disableDataPoolFactory>false</disableDataPoolFactory>
<!-- By default, the spring context file is setup to use lazy connections, that
is, using an @Transactional will only open a connection to the database
when a statement is actually sent to the DB. This improves performance but
you may revert back to the default Spring implementation by setting the
following flag to true -->
<disableLazyConnections>false</disableLazyConnections>
<!-- Set the following flag to true to enable the use of spring's PropertyPlaceholderConfigurer. Setting to false will make use of
PropertyOverrideConfigurer instead. Setting to true has the effect of forcing the end user of creating the override file rather
than relying on defaults. Optionally use a prefix for the variable names -->
<enablePropertyPlaceholderConfigurer prefix="yourprojectName." suppressBean="false">false</enablePropertyPlaceholderConfigurer>
<!-- Enable database version check. This will enable both the hibernate
table check as per Hibernate documentation as well as add a custom check
during startup to make sure that the database we're running is the same one
as what was seen during code generation time. Comment out this section
to completely ignore db version checking.
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
defaultFields = comma-separated list of fields to use during version check.
whereClause = anything to append to the SELECT clause to obtain the value
orderBy = anything to pass on to the ORDER BY clause to fix a sorting order
Except section: Override the default values. Eg: Enable all checks for all
schemas (defaultEnable=true) except schema someSchema.
Prefix fields with ">=" to signify version must be greater or equal to the values found.
-->
<versionCheck defaultEnabled="true" defaultTable="db_version" defaultFields="branch, alter_no, system, >=minor" whereClause="system='SOMESYSTEM'" orderBy="somefield">
<except schema="someSchema" table="db_version" fields="branch, alter_no" enabled="false" whereClause="system='SOMETHINGELSE'" orderBy="somefield"/>
</versionCheck>
<!-- If you prefer, you can add a suffix to each of the generated classes.
This is useful if you deal with Business Objects instead and would like
YourClass to refer to your BO and YourClassMO to reflect your (generated)
model object. Wildcard "*" accepted. Default: no suffix -->
<!--
<suffix default="MO">
<except package="yourpackage" class="yourclass" suffix="MO" />
</suffix>
-->
<!-- This adds @Cache to the top of each model object. The values correspond to CacheConcurrencyStrategy -->
<!--
<cache default="NONSTRICT_READ_WRITE" enabled="false">
<except package="*" class="yourclass" strategy="NONE" />
</cache>
-->
<!-- The maven section affects the generated pom.xml. Note: You'll need
to set enabled=true for any of this to take. If noArtifactVersions is set to true, the artifact references will not include a version so
you will need to include these in your parent poms instead.
noDeps=true will suppress all dependencies
useExternalLib=true will use the external hibernate pom.
enablePomGeneration=true will create a pom.xml
javaVersion=string to set as version no in maven-compiler-plugin. Default = 1.7
-->
<maven enabled="true" enablePomGeneration="true" javaVersion="1.7" artifactId="some-artifact" groupId="com.yourgroupid" version="1.3" name="Some friendly name" noArtifactVersions="false" noDeps="false" useExternalLib="false">