Compare commits

...

216 Commits

Author SHA1 Message Date
Yang Tang
e4bc1cdf1e
#3884 Ensure NullValuePropertyMappingStrategy.SET_TO_DEFAULT initializes empty collection/map when target is null
Signed-off-by: TangYang <tangyang9464@163.com>
2025-06-15 08:29:45 +02:00
Filip Hrisafov
c90c93630e #3886: Records do not have property write accessors (apart from the record components) 2025-06-14 23:40:02 +02:00
Filip Hrisafov
f4d1818171 Fix issue key in Issue3807Test 2025-06-14 21:33:26 +02:00
dependabot[bot]
d68819a233 Bump org.springframework:spring-context from 6.2.2 to 6.2.7 in /parent
Bumps [org.springframework:spring-context](https://github.com/spring-projects/spring-framework) from 6.2.2 to 6.2.7.
- [Release notes](https://github.com/spring-projects/spring-framework/releases)
- [Commits](https://github.com/spring-projects/spring-framework/compare/v6.2.2...v6.2.7)

---
updated-dependencies:
- dependency-name: org.springframework:spring-context
  dependency-version: 6.2.7
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-14 17:02:12 +02:00
Filip Hrisafov
46ce011e4b
Refactor options and add an enum (#3877) 2025-06-01 07:52:18 +02:00
Filip Hrisafov
9847eaf195
#3876: Move Windows and Mac OS builds outside of the main workflow 2025-05-31 18:14:13 +02:00
Yang Tang
ce84c81de2
#3659: Support @AnnotatedWith on decorators
Signed-off-by: TangYang <tangyang9464@163.com>
2025-05-31 17:52:05 +02:00
Yang Tang
bff88297e3
#3807: Properly recognize the type of public generic fields
Signed-off-by: TangYang <tangyang9464@163.com>
2025-05-31 13:29:39 +02:00
Yang Tang
8fc97f5f62
#3806: Properly apply NullValuePropertyMappingStrategy.IGNORE for collections / maps without setters
Signed-off-by: TangYang <tangyang9464@163.com>
2025-05-31 11:13:50 +02:00
Yang Tang
5464c3cff8
#3711: Support generic @Context
Signed-off-by: TangYang <tangyang9464@163.com>
2025-05-31 11:10:24 +02:00
Aleksey Ivashin
6b6600c370
#1958: Add support for ignoring multiple target properties at once 2025-05-25 17:05:18 +02:00
Yang Tang
0badba7003
#3849: Resolve duplicate invocation of overloaded lifecycle methods with inheritance
Add compiler option `mapstruct.disableLifecycleOverloadDeduplicateSelector` to disable the deduplication if needed.

Signed-off-by: TangYang <tangyang9464@163.com>
2025-05-25 16:35:38 +02:00
Yang Tang
3a5c70224d
#3809 Fix conditional mapping with @TargetPropertyName failing for nested update mappings
Signed-off-by: TangYang <tangyang9464@163.com>
2025-05-25 15:40:43 +02:00
Şamil Can
42c87d1da9
#3848: Mark String to number as lossy conversion 2025-05-25 15:22:47 +02:00
Dennis Melzer
05f27e96e2
#3852 Initialize Optionals with empty instead of null 2025-05-25 14:58:23 +02:00
Yang Tang
6e6fd01a2e
#3821: Add support for custom exception for subclass exhaustive strategy for @SubclassMapping
---------

Signed-off-by: TangYang <tangyang9464@163.com>
2025-05-17 18:40:51 +02:00
roelmang
fce73aee6a #3729 Support for using inner class Builder without using static factory method 2025-05-11 21:58:47 +02:00
Filip Hrisafov
2fb5776350 Add release notes for next version 2025-05-11 20:07:53 +02:00
zral
602e29083f
#1140 Add warning when target has no properties 2025-05-11 19:59:59 +02:00
Cause Chung
2c84d04463 #3240 Add Support for Java21 SequencedSet and SequencedMap 2025-05-11 17:33:35 +02:00
dependabot[bot]
668eeb5de1 Bump com.google.protobuf:protobuf-java from 3.21.7 to 3.25.5 in /parent
Bumps [com.google.protobuf:protobuf-java](https://github.com/protocolbuffers/protobuf) from 3.21.7 to 3.25.5.
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Changelog](https://github.com/protocolbuffers/protobuf/blob/main/protobuf_release.bzl)
- [Commits](https://github.com/protocolbuffers/protobuf/compare/v3.21.7...v3.25.5)

---
updated-dependencies:
- dependency-name: com.google.protobuf:protobuf-java
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-11 15:57:52 +02:00
fml2
d5f825193c
#3815: chore(docs): Improved wording about @Condition usage 2025-05-10 14:12:20 +02:00
Zegveld
39551242d7
#3786: Improve error message when mapping non-iterable to array 2025-01-24 14:41:35 +01:00
Filip Hrisafov
c08ba4ca7e
Update setup-java and checkout actions to v4 (#3804) 2025-01-22 08:51:49 +01:00
Filip Hrisafov
57d4f88a48
Java EA GitHub Actions improvements (#3803)
* Use Java 17 for building MapStruct (still Java 8 compatible)
* Upgrade to Spring 6 for tests
* Adjust excludes and min tests version for some integration tests
2025-01-20 07:56:19 +01:00
Filip Hrisafov
e0a7d3d0e6 Use latest Maven Wrapper 2025-01-19 15:05:59 +01:00
Tran Ngoc Nhan
8f96291911
Fix documentation typo and code polish (#3787) 2025-01-18 13:04:42 +01:00
Daniel Hammer
4812d2b030
Align README with v1.6.3 release (#3784) 2024-12-07 14:57:13 +01:00
jinhyogyeom
f98a742f98
Standardize Class Names to PascalCase in tests (#3773) 2024-12-01 11:22:51 +01:00
Tran Ngoc Nhan
084cf3abc1
Fix javadoc typos (#3780) 2024-11-29 09:33:41 +01:00
dudxor4587
f3d2b2e65b
Delete unnecessary conditions and modify return statement (#3772) 2024-11-21 23:14:16 +01:00
Roman Obolonskyi
737af6b50a
#3628 Add support for locale parameter for numberFormat and dateFormat 2024-11-17 16:46:59 +01:00
Minji Kim
bee983cd3c
Fix typos in comments (#3769) 2024-11-15 22:13:36 +01:00
hsjni0110
8de18e5a65
fix typos in method and variable names (#3766) 2024-11-13 21:35:20 +01:00
cussle
0df3f6af95
docs & refactor: fix typos and improve readability in multiple classes (#3767)
- AnnotatedConstructor: Fixed a variable name typo (noArgConstructorToInBecluded → noArgConstructorToBeIncluded).
- AbstractBaseBuilder: Improved Javadoc by fixing typos and clarifying wording.
- SourceRhsSelector: Corrected a typo in the class-level Javadoc.
- InheritanceSelector: Enhanced readability by fixing typos and refining comments.
2024-11-13 21:22:57 +01:00
GitHub Action
5bf2b152af Next version 1.7.0-SNAPSHOT 2024-11-09 11:40:01 +00:00
GitHub Action
b4e25e49de Releasing version 1.6.3 2024-11-09 11:31:12 +00:00
Filip Hrisafov
772fae4c77 Prepare release notes for 1.6.3 2024-11-09 12:20:14 +01:00
Filip Hrisafov
efdf435770 #3751 Improve readme to include support for Java 16+ records 2024-11-09 12:17:29 +01:00
Filip Hrisafov
c2bd847599 #3732 Do not generate obsolete imports for LocalDateTime <-> LocalDate conversion 2024-11-09 12:17:13 +01:00
Filip Hrisafov
21fdaa0f82 #3747 Do not generate redundant if condition with constructor mapping and RETURN_DEFAULT null value mapping strategy 2024-11-03 13:46:48 +01:00
Srimathi-S
32f1fea7b5
#3370 Prevent stack overflow error for Immutables with custom builder 2024-11-03 12:52:52 +01:00
Filip Hrisafov
26c5bcd923
Update readme with 1.6.2 2024-09-27 09:15:17 +02:00
GitHub Action
4e0d73db1d Next version 1.7.0-SNAPSHOT 2024-09-16 08:06:43 +00:00
GitHub Action
212607b447 Releasing version 1.6.2 2024-09-16 07:55:31 +00:00
Filip Hrisafov
4fd22d6b26 Prepare release notes for 1.6.2 2024-09-16 09:54:30 +02:00
Filip Hrisafov
a3b4139070 #3717 Fix ClassCastException when getting thrown types for a record accessor 2024-09-16 09:52:57 +02:00
GitHub Action
c74e62a94c Next version 1.7.0-SNAPSHOT 2024-09-15 16:01:43 +00:00
GitHub Action
10d69878a1 Releasing version 1.6.1 2024-09-15 15:52:17 +00:00
Filip Hrisafov
c36f9ae5d1 Prepare release notes for 1.6.1 2024-09-15 17:11:24 +02:00
Filip Hrisafov
3011dd77d7 #3678 before / after mapping for type using builder should only be kept if they are using the actual type in @TargetType or @MappingTarget 2024-09-15 16:45:21 +02:00
Filip Hrisafov
4c1df35ba6 #3703 Use include model instead of manually writing the type name for return type for afterMappingReferencesWithFinalizedReturnType 2024-09-15 16:45:08 +02:00
Filip Hrisafov
2686e852b6
#3661 Use correct type for the Record component read accessors 2024-09-14 01:17:45 +02:00
Filip Hrisafov
12c9c6c1f0 Use email variable for GitHub Bot git email 2024-09-06 16:35:37 +03:00
Filip Hrisafov
796dd94674 Update next release changelog with latest changes 2024-09-02 15:33:08 +02:00
Filip Hrisafov
5232df2707 Try to stabilise MapMappingTest and CarMapperTest 2024-09-02 15:18:37 +02:00
Obolrom
4d9894ba25
#3113 Use LinkedHashSet, LinkedHashSet new factory methods for java >= 19 2024-09-02 10:26:48 +02:00
김기서
23f4802374
Fix method name typo (#3691) 2024-09-02 09:05:01 +02:00
Obolrom
1e89d7497b
Fix method name typo (#3622) 2024-09-02 08:44:17 +02:00
hduelme
c6010c917a Fix typo in readme Maven plugin config 2024-08-31 16:34:54 +02:00
Filip Hrisafov
58dcb9d813
Update latest version and remove some obsolete badges 2024-08-28 11:56:21 +02:00
Filip Hrisafov
c89b616f8c
#3668 Do not apply implicit mappings when using SubclassExhaustiveStrategy#RUNTIME_EXCEPTION and return type is abstract 2024-08-24 12:22:37 +02:00
Filip Hrisafov
6c8a2e184b #3667, #3673 MappingReference should custom MappingOption equality instead of the default only target name based one 2024-08-24 11:29:28 +02:00
Filip Hrisafov
60cd0a4420
#3670 Fix regression when using InheritInverseConfiguration with nested target properties and reversing target = "." 2024-08-24 11:27:52 +02:00
Stefan Simon
b452d7f2c8
#3652 Inverse Inheritance should be possible for ignore-mappings without source 2024-08-18 17:46:35 +02:00
GitHub Action
96d0698417 Next version 1.7.0-SNAPSHOT 2024-08-12 21:08:07 +00:00
GitHub Action
38ec5c5335 Releasing version 1.6.0 2024-08-12 20:59:31 +00:00
thunderhook
81ca739040 #3638 Remove deprecation note of enum mapping via @Mapping 2024-07-25 10:40:12 +02:00
Filip Hrisafov
0f24633d04 Fix update website script to be able to run Linux 2024-07-20 18:05:08 +02:00
GitHub Action
6365a606c1 Next version 1.6.0-SNAPSHOT 2024-07-20 15:45:11 +00:00
GitHub Action
6ef64ea3aa Releasing version 1.6.0.RC1 2024-07-20 15:36:11 +00:00
Filip Hrisafov
bbb9bb403c Fix typo in changelog 2024-07-20 17:21:29 +02:00
Filip Hrisafov
5ce9c537e9 Add release notes 2024-07-20 16:29:17 +02:00
Filip Hrisafov
e2edb1a086 #3504 Add example classes for the passing target type documentation 2024-07-20 16:26:38 +02:00
Stefan Simon
3047760fd0
#3591 Fix duplicate method generation with recursive auto mapping 2024-07-20 16:19:59 +02:00
Obolrom
df49ce5ff9
#3609 Pass bean mapping ignored unmapped source properties to subclass forged methods
Co-authored-by: thunderhook <8238759+thunderhook@users.noreply.github.com>
2024-07-20 14:06:49 +02:00
Filip Hrisafov
66f4288842
#3601 Always use SourceParameterCondition when checking source parameter
This is a breaking change, with this change whenever a source parameter is used as a source for a target property the condition has to apply to source parameters and not properties
2024-07-20 13:53:39 +02:00
thunderhook
52877d36c2 #3634 fix typo in experimental note 2024-07-20 13:06:00 +02:00
thunderhook
eef3bdfca4 #3639 fix documentation link 2024-07-20 13:05:28 +02:00
hduelme
8fa2f40944
Enforce whitespaces around the for colon with CheckStyle (#3642) 2024-07-15 23:18:32 +02:00
Connor McGowan
037da5a1e1
#3635 Fix documentation of unmappedSourcePolicy default (#3637) 2024-07-07 21:19:38 +02:00
Filip Hrisafov
69371708ee
#3574 Respect only explicit mappings but fail on unmapped source fields
* #3574 Respect only explicit mappings but fail on unmapped source fields

This reverts #2560, because we've decided that `@BeanMapping(ignoreByDefault = true)` should only be applied to target properties and not to source properties.
Source properties are anyway ignored, the `BeanMapping#unmappedSourcePolicy` should be used to control what should happen with unmapped source policy
2024-07-06 10:31:32 +02:00
Filip Hrisafov
babb9dedd9 #3602 Doing a release should reset NEXT_RELEASE_CHANGELOG.md 2024-06-30 14:47:27 +02:00
Filip Hrisafov
baa02bf377 #3602 Fix path for update-website.sh scrip in release workflow 2024-05-11 09:32:41 +02:00
GitHub Action
8a679b325d Next version 1.6.0-SNAPSHOT 2024-05-11 07:10:47 +00:00
GitHub Action
21a8b88a0f Releasing version 1.6.0.Beta2 2024-05-11 07:01:58 +00:00
Filip Hrisafov
8e53b4181f #3602 Fix setup-java action for release workflow 2024-05-11 08:47:39 +02:00
Filip Hrisafov
9a5e6b1892
#3602 Automate release with JReleaser
Add JReleaser for automating the release and add a step for automating the publishing of the website
2024-05-11 08:27:20 +02:00
Filip Hrisafov
b33942a010 #3561 Add test case 2024-05-01 08:15:44 +02:00
Filip Hrisafov
0a2a0aa526
#2610 Add support for conditions on source parameters + fix incorrect use of source parameter in presence check method (#3543)
The new `@SourceParameterCondition` is also going to cover the problems in #3270 and #3459.
The changes in the `MethodFamilySelector` are also fixing #3561
2024-04-29 08:05:52 +02:00
Filip Hrisafov
0a935c67a7 #3565 Presence check methods should not be considered as valid mapping candidates 2024-04-28 20:22:53 +02:00
Zegveld
5fbd36c443
#3577 Improve Mapping#ignoreByDefault documentation 2024-04-28 20:20:11 +02:00
hduelme
8e66445fe9
#3564 Correct issue key for Issue3485Test 2024-04-02 12:00:41 +02:00
Oliver Erhart
e815e3cb1e
#3524 Provide tests with Lombok style super builders 2024-03-10 09:15:37 +01:00
hduelme
2c12e75bfc
#3485 Exception for Mapping to target = "." without source 2024-03-03 18:59:32 +01:00
Filip Hrisafov
c374b5267f
#3360 Do not report unmapped source and target properties when result type is abstract due to runtime exception subclass exhaustive strategy (#3526) 2024-02-11 19:53:38 +01:00
Zegveld
bb1cd63485
#2788 Improve unmapped source properties message for forged methods 2024-02-11 13:29:34 +01:00
Filip Hrisafov
ca1fd0d85d
#3331 Do not handle defined mappings if the result type is abstract due to runtime exception subclass exhaustive strategy (#3487) 2024-02-11 12:51:19 +01:00
Oliver Erhart
8191c850e0
#3323 Support access to the source property name 2024-02-11 10:42:23 +01:00
hduelme
0a43bc088f
Add missing generic type to Javadoc Builder (#3499) 2024-01-28 18:07:57 +01:00
hduelme
90a3ce0b46
Use primitive types in NativeTypes (#3501) 2024-01-28 18:06:42 +01:00
Chanyut Yuvacharuskul
6830258f77
Fix typo in chapter-10-advanced-mapping-options.asciidoc (#3500) 2024-01-28 17:51:57 +01:00
hduelme
6322138028
Add missing generic diamond operator to MappingOptions (#3498) 2024-01-28 17:50:33 +01:00
Filip Hrisafov
60f162ca88
#3463 DefaultBuilderProvider should be able to handle methods in parent interfaces 2024-01-28 17:47:39 +01:00
Filip Hrisafov
6cb126cd7c
#3462 Stream getters should not be treated as alternative setter 2023-12-31 09:34:34 +01:00
Oliver Erhart
7e6fee8714
#1064 Provide a switch to turn off CheckStyle on generated test sources 2023-12-27 13:40:04 +01:00
Filip Hrisafov
6d99f7b8f3
#3473 Add Java 21 and EA to build matrix
Fix tests not running green on Java 21
Update Spring to run correctly on Java 21
2023-12-18 07:35:26 +01:00
mosesonline
fa857e9ff4
bump some lib versions (#3460) 2023-12-10 15:26:47 +01:00
Ravil Galeyev
930f5709b6
#3400 Remove unnecessary casts to long and double 2023-11-29 22:25:22 +01:00
Muhammad Usama
2bb2aefed8
#3413 Using Mapping#expression and Mapping#conditionaQualifiedBy(Name) should lead to compile error 2023-11-24 06:34:15 +01:00
wandi34
2af291ce2f
Fix Typo Mappper in SubclassMapping Doc 2023-11-11 21:48:52 +01:00
Filip Hrisafov
04deac2b3a [maven-release-plugin] prepare for next development iteration 2023-11-04 23:06:17 +01:00
Filip Hrisafov
0ac0c42dbc [maven-release-plugin] prepare release 1.6.0.Beta1 2023-11-04 23:06:16 +01:00
Oliver Erhart
79f01e2de0
Change master to main branch and fix CI status badge (#3423) 2023-11-04 21:35:40 +01:00
Oliver Erhart
b77d321ffb
Added recent contributors (including myself) 2023-11-01 00:01:45 +01:00
Xiu Hong Kooi
5d39314bd2
#3376 support mapping from iterables to collection 2023-10-31 23:55:11 +01:00
Filip Hrisafov
c59eca2a77
#3361 Inheriting mappings should only be applied if the target has been redefined 2023-09-30 21:52:07 +02:00
dependabot[bot]
97c389d58b Bump org.codehaus.plexus:plexus-utils from 3.0.20 to 3.0.24 in /parent
Bumps [org.codehaus.plexus:plexus-utils](https://github.com/codehaus-plexus/plexus-utils) from 3.0.20 to 3.0.24.
- [Release notes](https://github.com/codehaus-plexus/plexus-utils/releases)
- [Commits](https://github.com/codehaus-plexus/plexus-utils/compare/plexus-utils-3.0.20...plexus-utils-3.0.24)

---
updated-dependencies:
- dependency-name: org.codehaus.plexus:plexus-utils
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-30 11:11:47 +02:00
Nikolas Charalambidis
032ee4d77a #3374 Lombok compatibility documentation 2023-09-17 09:44:31 +02:00
GVladi
f61a3acec3 #3089 Improve support for Map attributes for Immutables
Co-Authored-By: thunderhook <8238759+thunderhook@users.noreply.github.com>
2023-09-16 10:56:52 +02:00
Filip Hrisafov
ea997f83ce
#2340 Add FUNDING.yml 2023-08-19 10:09:36 +02:00
Ben Zegveld
8cc2bdd092 #3163: Strip wild card when checking for type assignability 2023-08-13 09:26:53 +02:00
Zegveld
721288140a
Feature/2663 (#3007)
#2663 Fix for 2-step mapping with generics.

---------

Co-authored-by: Ben Zegveld <Ben.Zegveld@gmail.com>
2023-08-04 10:14:53 +02:00
Filip Hrisafov
812faeef51 Use presence checks for checking source parameter presence
Instead of explicitly doing a null check use a PresenceCheck mechanism for
* BeanMappingMethod
* ContainerMappingMethod
* MapMappingMethod
2023-08-01 15:41:19 +02:00
Anton Erofeev
b2dc64136d
#3292 Simplify expressions, remove redundant expressions 2023-08-01 14:17:50 +02:00
Venkatesh Prasad Kannan
279ab22482
#3309 Add BeanMapping#unmappedSourcePolicy 2023-08-01 09:48:20 +02:00
Filip Hrisafov
28d827a724 Add test case for subclass mapping and bean mapping ignore by default 2023-07-30 10:39:10 +02:00
Lucas Resch
0460c373c0
#3229: Implement InjectionStrategy.SETTER 2023-07-30 10:38:24 +02:00
Roberto Oliveira
230e84efd1 #3340 Update tarLongFileMode to use POSIX 2023-07-29 09:13:55 +02:00
Filip Hrisafov
4abf2d4202 #3317 Do not generate source parameter if check for only primitives 2023-07-09 15:01:06 +02:00
Filip Hrisafov
53c73324ff #3310 Make sure that adders work properly when they are in a generic class 2023-07-09 15:00:57 +02:00
Zegveld
04434af17a
#3296: Skip default and static methods when determining prototype methods 2023-07-08 18:03:56 +02:00
dependabot[bot]
1b1325da6d Bump guava from 29.0-jre to 32.0.0-jre in /parent
Bumps [guava](https://github.com/google/guava) from 29.0-jre to 32.0.0-jre.
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

---
updated-dependencies:
- dependency-name: com.google.guava:guava
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-16 12:37:01 +02:00
Filip Hrisafov
86919c637f
#3144 Map to Bean should only be possible for single source mappings and if explicitly used in multi source mappings 2023-05-28 09:55:40 +02:00
Filip Hrisafov
d075d9a5b6 Upgrade Freemarker to 2.3.32 2023-05-27 15:55:15 +02:00
Filip Hrisafov
62d1bd3490
#3280 Refactor method selection and use a context to be able to more easily access information 2023-05-27 15:04:34 +02:00
Filip Hrisafov
c2eed45df1 #3126 Apply target this references in the BeanMappingMethod 2023-05-27 11:17:01 +02:00
Oliver Erhart
51f4e7eba9
#3231 Prefer record constructor annotated with @Default 2023-05-24 06:04:13 +02:00
José Carlos Campanero Ortiz
84c443df9c
#3245 Remove redundant null checks in nested properties 2023-05-24 05:44:36 +02:00
Oliver Erhart
6d205e5bc4
#1454 Support for lifecycle methods on type being built with builders
Add missing support for lifecycle methods with builders:

* `@BeforeMapping` with `@TargetType` the type being build
* `@AftereMapping` with `@TargetType` the type being build
* `@AfterMapping` with `@MappingTarget` the type being build
2023-05-21 22:49:41 +02:00
paparadva
7c90592d05 #2863 Add validation of String type to @TargetPropertyName 2023-05-21 22:21:34 +02:00
Filip Hrisafov
efaa67aadf #3104 Update methods with NullValuePropertyMappingStrategy.IGNORE should use SetterWrapperForCollectionsAndMapsWithNullCheck 2023-05-20 17:04:59 +02:00
Filip Hrisafov
a89c34f00c #3238 Compile error instead of null pointer exception for invalid ignore with target this 2023-05-20 17:04:22 +02:00
Jason Bodnar
d0e4c48228
#3172 Add mapping between Locale and String 2023-05-08 22:23:03 +02:00
Zegveld
bc5a877121
#3054: Allow abstract return type when all directly sealed subtypes are covered by subclass mappings
Co-authored-by: Ben Zegveld <Ben.Zegveld@gmail.com>
2023-05-01 11:54:24 +02:00
dependabot[bot]
be94569791 Bump protobuf-java from 3.21.2 to 3.21.7 in /parent
Bumps [protobuf-java](https://github.com/protocolbuffers/protobuf) from 3.21.2 to 3.21.7.
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Changelog](https://github.com/protocolbuffers/protobuf/blob/main/generate_changelog.py)
- [Commits](https://github.com/protocolbuffers/protobuf/compare/v3.21.2...v3.21.7)

---
updated-dependencies:
- dependency-name: com.google.protobuf:protobuf-java
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-01 11:32:21 +02:00
MengxingYuan
f3dac94701
#2781 Remove unmapped source properties when source parameter is directly mapped 2023-05-01 10:28:51 +02:00
Etien Rožnik
4843123e6e
#3165 Support adders for array / iterable to collection 2023-05-01 09:42:58 +02:00
José Carlos Campanero Ortiz
a8df94cc20
#2987 Support for defining Javadoc in the generated mapper implementation 2023-05-01 09:22:59 +02:00
todzhang's cloudsdocker
970984785d
Update one typo in JavaDoc (#2938) 2023-05-01 09:12:23 +02:00
Bragolgirith
d3b4a168b7
#3199 Add support for implicit conversion between java.time.LocalDate and java.time.LocalDateTime 2023-05-01 09:11:05 +02:00
ro0sterjam
931591a385
#3071 Support defining custom processor options by custom SPI 2023-04-30 17:02:39 +02:00
Zegveld
2f78d3f4e2
#3125: Allow subclassmapping inheritance for methods with identical signature
Co-authored-by: Ben Zegveld <Ben.Zegveld@gmail.com>
2023-04-30 16:33:00 +02:00
Filip Hrisafov
1ab5db6a27
Update latest release version to 1.5.5.Final 2023-04-23 22:20:05 +02:00
Filip Hrisafov
86a668661a #3159 Do null value check for collections with default expression 2023-04-23 18:30:08 +02:00
Filip Hrisafov
1bc3436c5c #3239 Mapping composition is no longer experimental 2023-04-22 22:31:03 +02:00
Filip Hrisafov
979b35a2f4 #3153 Do not use compress directive to strip whitespaces for value mapping switch method
When using the compress directive it is going to strip whitespaces from the templates as well (i.e. what the user defined in `ValueMapping#source` and / or `ValueMapping#target
2023-04-22 19:32:02 +02:00
Filip Hrisafov
e69843f46e #3158 BeanMapping#ignoreByDefault should work properly for constructor properties 2023-04-22 19:31:30 +02:00
Filip Hrisafov
c6ea69eaf9 #3186 Do not use conversions in 2-step mapping when they are disabled 2023-04-22 19:31:01 +02:00
Filip Hrisafov
d10d48ccff #3248 BeanMapping#ignoreUnmappedSourceProperties should be inherited for @InheritConfiguration 2023-04-22 19:21:28 +02:00
Claudio Nave
b1034e6703 #3202 Improve line location report for invalid qualifier for SubclassMapping 2023-04-22 18:16:07 +02:00
Filip Hrisafov
9adcb06c34 #3236 Add missing jakarta-cdi to the documentation 2023-04-22 17:46:27 +02:00
Filip Hrisafov
00f891be58 #3112 Add missing brackets 2023-04-22 17:14:46 +02:00
Johnny Lim
3c81d36810
Polish links in docs (#3214) 2023-04-16 21:51:33 +02:00
Filip Hrisafov
162fdb44f4
#3195 Update the location for asking questions 2023-04-16 10:17:32 +02:00
Ben Zegveld
03563d8ffe #3174 Also allow multiple SubclassMapping annotations on an annotation @interface. 2023-04-15 18:31:12 +02:00
Filip Hrisafov
6e9fa87ba9
#3142 Nested forged methods should declare throws from lifecycle methods 2023-04-13 21:52:15 +02:00
Filip Hrisafov
2be1f306a1 #3135 BeanMapping#mappingControl should be inherited by forged methods 2023-04-13 21:50:40 +02:00
José Carlos Campanero Ortiz
62c7ce1cdf
#3112 Document <THROW_EXCEPTION> in the reference guide 2023-04-13 21:48:13 +02:00
Claudio Nave
89db26a1af
#3119 Add qualifiedBy and qualifiedByName to SubclassMapping annotation 2023-03-17 09:06:13 +01:00
Claudio Nave
a7ba12676d
#3110 Fix throws declaration for ValueMapping annotated methods (#3122)
#3110 Fix throws declaration for ValueMapping annotated methods
2023-02-05 12:17:02 +01:00
Filip Hrisafov
fd27380185
#2953 Add support for globally defining nullValueMapMappingStrategy and nullValueIterableMappingStrategy 2022-11-13 14:22:25 +01:00
Filip Hrisafov
82b19b0d8a #3077 Add test case 2022-11-13 14:21:03 +01:00
Zegveld
8894cd5935
#3057: limit do not allow self to subclassmappings. (#3063)
* #3057: limit do not allow self to subclassmappings.
* #3057: determine method candidates after all other fields are set in the constructor.

Co-authored-by: Ben Zegveld <Ben.Zegveld@gmail.com>
Co-authored-by: Filip Hrisafov <filip.hrisafov@gmail.com>
2022-11-04 14:21:05 +01:00
Filip Hrisafov
16e3ceadec
#2952 Do not treat a getter as an alternative write accessor when using CollectionMappingStrategy#TARGET_IMMUTABLE 2022-11-03 23:29:47 +01:00
Orange Add
93f7c3b8ea
#3015 Fix annotations to the forged methods 2022-11-03 23:22:35 +01:00
Orange Add
6a394ad466
#3037 Support @ValueMapping in meta annotations 2022-11-03 23:21:43 +01:00
Orange Add
bb099a55ee
#3040: Allow using only BeanMapping#mappingControl 2022-11-03 22:02:58 +01:00
Filip Hrisafov
81b2f70dac #3039 Upgrade FreeMarker to 2.3.31 2022-11-03 21:49:06 +01:00
Filip Hrisafov
a5d3542c24 Update latest release version to 1.5.3.Final 2022-10-07 20:43:15 +02:00
Filip Hrisafov
481ab36ca3 #3036 Add missing exclude to full feature test 2022-10-03 21:16:25 +02:00
Filip Hrisafov
3a325ea66b
#3036 Fix compile errors when intersection types are used in lifecycle methods 2022-10-03 21:12:19 +02:00
Filip Hrisafov
266c5fa41c
#1216 Pick candidate method with most specific return type
When there are multiple candidate methods returning different types.
We should be able to use the method with the most specific return type (if such a method exists)
2022-10-02 19:20:13 +02:00
Zegveld
411cc24dac
#2955 Fix @AfterMapping with return type not called for update mappings 2022-10-02 09:34:03 +02:00
José Carlos Campanero Ortiz
90a487ac06
#1427 Add support for custom name in Spring stereotype annotations 2022-10-01 13:47:49 +02:00
Filip Hrisafov
af1eab0ece
#2743 BeanMappingOptions should not be inherited for forged methods 2022-09-29 22:10:27 +02:00
Zegveld
608d476ed2
#3018: Use MappingControl with SubclassMapping 2022-09-29 21:35:51 +02:00
Orange Add
e979f506fa
#2773 Copy @Deprecated annotation from method or mapper to implementation 2022-09-28 22:17:59 +02:00
Filip Hrisafov
73e8fd6152
#2840, #2913, #2921: MethodMatcher should not match widening methods
In the MethodMatcher we need to do a special check when the target type is primitive.
The reason for that is that a Long is assignable to a primitive double.
However, doing that means that information can be lost and thus we should not pick such methods.
When the target type is primitive, then a method will be matched if and only if boxed equivalent of the target type is assignable to the boxed equivalent of the candidate return type
2022-09-27 09:35:54 +02:00
Johnny Lim
811cd569bb
Javadoc and documentation polishing (#3026) 2022-09-26 19:02:01 +02:00
Filip Hrisafov
8d670e7db7 #3008 Replace old issue template with new GitHub issue form templates 2022-09-21 22:10:42 +02:00
Prasanth Omanakuttan
d593afed69
Avoid unnecessary unboxing of Boolean (#3003) 2022-09-12 18:45:22 +02:00
José Carlos Campanero Ortiz
97c6755288
#2963 Add support for enum to integer conversion 2022-09-04 13:58:10 +02:00
Iaroslav Bogdanchikov
bbf63ae177
#2730 Add support for Jakarta XML Binding 2022-09-02 22:04:01 +02:00
Filip Hrisafov
21069e5a2e #2895 Generate more readable annotations 2022-09-02 17:24:37 +02:00
Prasanth Omanakuttan
68571de01b Update Typos in java-doc
Closes #2989
2022-08-29 21:32:00 +02:00
Orange Add
3cc2aa7675
#2825 Fix SubclassMapping stackoverflow exception 2022-08-28 12:41:25 +02:00
Orange Add
ac356cab25
#2983 Add @AnnotateWith support to non bean mapping methods 2022-08-28 12:33:46 +02:00
Filip Hrisafov
4708f4b2aa #2950 Disable CDI in the full features tests on Java 8 2022-08-26 19:36:51 +02:00
Filip Hrisafov
4fa66229d9
#2990 Stabilise top level imports 2022-08-26 19:35:54 +02:00
Taihao Zhang
3f798744ac
Fix typo in docs (#2982) 2022-08-24 19:40:08 +02:00
Filip Hrisafov
853e7b27df
#2925 Fix IllegalArgumentException when resolving generic parameters
When resolving the parameter for a method like:

```
<T> Optional<T> from(T value)
```

There was an exception in javac because getting a DeclaredType from an Optional
with a primitive type argument throws an exception.
Therefore, when assigning the type arguments we get the boxed equivalent.
This problem does not happen in the Eclipse compiler
2022-08-24 19:39:09 +02:00
Filip Hrisafov
42500ca755 #2907 Add test case for nested import of array 2022-08-24 19:38:40 +02:00
Filip Hrisafov
71b1a7b8a2 #2945 Stabilise top level imports
Make sure that GeneratedType always gets the imported types
from a Type before adding them
2022-08-24 19:38:40 +02:00
Filip Hrisafov
b24e831cf0
#2937 Fix conditional check for collections with adders 2022-08-24 19:11:52 +02:00
Filip Hrisafov
237543c47c
#2897 Always import types defined in Mapper#imports 2022-08-24 18:59:31 +02:00
Filip Hrisafov
fd4a2548b3 #2928 Add IntelliJ and Eclipse plugin information 2022-08-24 18:55:05 +02:00
Filip Hrisafov
874bf1fd2c
#2950 Add support for Jakarta CDI 2022-08-24 18:38:44 +02:00
Filip Hrisafov
ef4c26b075
#2949 Do not inverse inherit BeanMapping#ignoreUnmappedSourceProperties 2022-08-24 18:36:43 +02:00
Filip Hrisafov
3e0c62ac36 Publish snapshots when on main 2022-08-21 11:26:42 +02:00
Filip Hrisafov
4118a44630 #2974 Fix typos in documentation
Closes #2974
2022-08-21 10:56:25 +02:00
Hakan
54321d6e66
#2839 Keep thrown types when creating a new ForgedMethod with the same arguments
This fixes a compilation error when mapping fields with the same type due to not wrapping in a `try-catch` block
2022-08-20 15:23:32 +02:00
Prasanth Omanakuttan
46900cabde
Update Typos in javadoc (#2958) 2022-08-20 13:37:43 +02:00
Zegveld
17997ef617
#2901: Fix @TargetType annotation on a @Condition annotated method for a Collection value 2022-08-20 13:01:47 +02:00
Zegveld
849085e026
#1574: Support for annotating the generated code with custom annotations
Add new `@AnnotateWith` annotation.
This annotation can be used to instruct the MapStruct processor
to generate custom annotations in the generated code.
2022-08-20 12:59:38 +02:00
Nikola Ivačič
8fa286fe4c #2688: Support accessing to the target property name 2022-08-01 19:17:33 +02:00
1002 changed files with 34788 additions and 2828 deletions

2
.github/FUNDING.yml vendored Normal file
View File

@ -0,0 +1,2 @@
github: mapstruct
open_collective: mapstruct

45
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View File

@ -0,0 +1,45 @@
name: Bug report
description: Create a report and help us improve
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
Please fill in all required fields with as many details as possible.
- type: textarea
id: expected
attributes:
label: Expected behavior
description: |
Describe what you were expecting MapStruct to do
placeholder: |
Here you can also add the generated code that you would like MapStruct to generate
- type: textarea
id: actual
attributes:
label: Actual behavior
description: |
Describe what you observed MapStruct did instead
placeholder: |
Here you can also add the generated code that MapStruct generated
- type: textarea
id: steps
attributes:
label: Steps to reproduce the problem
description: |
- Share your mapping configuration
- An [MCVE (Minimal Complete Verifiable Example)](https://stackoverflow.com/help/minimal-reproducible-example) can be helpful to provide a complete reproduction case
placeholder: |
Share your MapStruct configuration
validations:
required: true
- type: input
id: mapstruct-version
attributes:
label: MapStruct Version
description: |
Which MapStruct version did you use?
Note: While you can obviously continue using older versions of MapStruct, it may well be that your bug is already fixed. If you're using an older version, please also try to reproduce the bug in the latest version of MapStruct before reporting it.
placeholder: ex. MapStruct 1.5.2
validations:
required: true

16
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@ -0,0 +1,16 @@
contact_links:
- name: MapStruct Discussions
url: https://github.com/mapstruct/mapstruct/discussions
about: Please use the MapStruct GitHub Discussions for open ended discussions and to reach out to the community.
- name: Stack Overflow
url: https://stackoverflow.com/questions/tagged/mapstruct
about: For questions about how to use MapStruct, consider asking your question on Stack Overflow, tagged [mapstruct].
- name: Documentation
url: https://mapstruct.org/documentation/stable/reference/html/
about: The MapStruct reference documentation.
- name: Gitter Chat
url: https://gitter.im/mapstruct/mapstruct-users
about: For realtime communication with the MapStruct community, consider writing in our Gitter chat room.
- name: MapStruct Examples
url: https://github.com/mapstruct/mapstruct-examples
about: Some examples of what can be achieved with MapStruct. (contributions are always welcome)

View File

@ -0,0 +1,43 @@
name: Feature Request
description: Suggest an idea
body:
- type: markdown
attributes:
value: |
Please describe the use-case you have. This will better help us understand the context in which you're looking for a new feature.
- type: textarea
id: use-case
attributes:
label: Use case
description: |
Please describe the use-case you have. This will better help us understand the context in which you're looking for a new feature.
placeholder: Describe the use-case here
validations:
required: true
- type: textarea
id: solution
attributes:
label: Generated Code
description: |
Please describe the possible generated code you'd like to see in MapStruct generate.
Please note, it's not always easy to describe a good solution. Describing the use-case above is much more important to us.
placeholder: Describe the possible solution here.
validations:
required: false
- type: textarea
id: workarounds
attributes:
label: Possible workarounds
description: |
Please describe the possible workarounds you've implemented to work around the lacking functionality.
placeholder: Describe the possible workarounds here.
validations:
required: false
- type: input
id: mapstruct-version
attributes:
label: MapStruct Version
description: What MapStruct version and edition did you try?
placeholder: ex. MapStruct 1.5.2
validations:
required: false

82
.github/scripts/update-website.sh vendored Normal file
View File

@ -0,0 +1,82 @@
#!/bin/bash
#
# Copyright MapStruct Authors.
#
# Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
#
# env vars:
# VERSION
# GH_BOT_EMAIL
# This script has been inspired by the JReleaser update-website.sh (https://github.com/jreleaser/jreleaser/blob/main/.github/scripts/update-website.sh)
set -e
function computePlainVersion() {
echo $1 | sed 's/\([[:digit:]]*\)\.\([[:digit:]]*\)\.\([[:digit:]]*\).*/\1.\2.\3/'
}
function computeMajorMinorVersion() {
echo $1 | sed 's/\([[:digit:]]*\)\.\([[:digit:]]*\).*/\1.\2/'
}
function isStable() {
local PLAIN_VERSION=$(computePlainVersion $1)
if [ "${PLAIN_VERSION}" == "$1" ]; then
echo "yes"
else
echo "no"
fi
}
STABLE=$(isStable $VERSION)
MAJOR_MINOR_VERSION=$(computeMajorMinorVersion $VERSION)
DEV_VERSION=`grep devVersion config.toml | sed 's/.*"\(.*\)"/\1/'`
MAJOR_MINOR_DEV_VERSION=$(computeMajorMinorVersion $DEV_VERSION)
STABLE_VERSION=`grep stableVersion config.toml | sed 's/.*"\(.*\)"/\1/'`
MAJOR_MINOR_STABLE_VERSION=$(computeMajorMinorVersion $STABLE_VERSION)
echo "📝 Updating versions"
SEDOPTION="-i"
if [[ "$OSTYPE" == "darwin"* ]]; then
SEDOPTION="-i ''"
fi
sed $SEDOPTION -e "s/^devVersion = \"\(.*\)\"/devVersion = \"${VERSION}\"/g" config.toml
if [ "${STABLE}" == "yes" ]; then
sed $SEDOPTION -e "s/^stableVersion = \"\(.*\)\"/stableVersion = \"${VERSION}\"/g" config.toml
if [ "${MAJOR_MINOR_STABLE_VERSION}" != ${MAJOR_MINOR_VERSION} ]; then
echo "📝 Updating new stable version"
# This means that we have a new stable version and we need to change the order of the releases.
sed $SEDOPTION -e "s/^order = \(.*\)/order = 500/g" data/releases/${MAJOR_MINOR_VERSION}.toml
NEXT_STABLE_ORDER=$((`ls -1 data/releases | wc -l` - 2))
sed $SEDOPTION -e "s/^order = \(.*\)/order = ${NEXT_STABLE_ORDER}/g" data/releases/${MAJOR_MINOR_STABLE_VERSION}.toml
git add data/releases/${MAJOR_MINOR_STABLE_VERSION}.toml
fi
elif [ "${MAJOR_MINOR_DEV_VERSION}" != "${MAJOR_MINOR_VERSION}" ]; then
echo "📝 Updating new dev version"
# This means that we are updating for a new dev version, but the last dev version is not the one that we are doing.
# Therefore, we need to update add the new data configuration
cp data/releases/${MAJOR_MINOR_DEV_VERSION}.toml data/releases/${MAJOR_MINOR_VERSION}.toml
sed $SEDOPTION -e "s/^order = \(.*\)/order = 1000/g" data/releases/${MAJOR_MINOR_VERSION}.toml
fi
sed $SEDOPTION -e "s/^name = \"\(.*\)\"/name = \"${VERSION}\"/g" data/releases/${MAJOR_MINOR_VERSION}.toml
sed $SEDOPTION -e "s/^releaseDate = \(.*\)/releaseDate = $(date +%F)/g" data/releases/${MAJOR_MINOR_VERSION}.toml
git add data/releases/${MAJOR_MINOR_VERSION}.toml
git add config.toml
echo "📝 Updating distribution resources"
tar -xf tmp/mapstruct-${VERSION}-dist.tar.gz --directory tmp
rm -rf static/documentation/${MAJOR_MINOR_VERSION}
cp -R tmp/mapstruct-${VERSION}/docs static/documentation/${MAJOR_MINOR_VERSION}
mv static/documentation/${MAJOR_MINOR_VERSION}/reference/html/mapstruct-reference-guide.html static/documentation/${MAJOR_MINOR_VERSION}/reference/html/index.html
git add static/documentation/${MAJOR_MINOR_VERSION}
git config --global user.email "${GH_BOT_EMAIL}"
git config --global user.name "GitHub Action"
git commit -a -m "Releasing version ${VERSION}"
git push

View File

@ -7,19 +7,15 @@ env:
jobs:
test_jdk_ea:
strategy:
fail-fast: false
matrix:
java: [19-ea]
name: 'Linux JDK ${{ matrix.java }}'
name: 'Linux JDK EA'
runs-on: ubuntu-latest
steps:
- name: 'Checkout'
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: 'Set up JDK'
uses: actions/setup-java@v3
uses: oracle-actions/setup-java@v1
with:
distribution: 'zulu'
java-version: ${{ matrix.java }}
website: jdk.java.net
release: EA
- name: 'Test'
run: ./mvnw ${MAVEN_ARGS} -Djacoco.skip=true install -DskipDistribution=true

20
.github/workflows/macos.yml vendored Normal file
View File

@ -0,0 +1,20 @@
name: Mac OS CI
on: push
env:
MAVEN_ARGS: -V -B --no-transfer-progress -Dhttp.keepAlive=false -Dmaven.wagon.http.pool=false -Dmaven.wagon.httpconnectionManager.ttlSeconds=120
jobs:
mac:
name: 'Mac OS'
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- name: 'Set up JDK 21'
uses: actions/setup-java@v4
with:
distribution: 'zulu'
java-version: 21
- name: 'Test'
run: ./mvnw ${MAVEN_ARGS} install

View File

@ -12,80 +12,49 @@ jobs:
strategy:
fail-fast: false
matrix:
java: [13, 17, 18]
java: [21]
name: 'Linux JDK ${{ matrix.java }}'
runs-on: ubuntu-latest
steps:
- name: 'Checkout'
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: 'Set up JDK'
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
distribution: 'zulu'
java-version: ${{ matrix.java }}
- name: 'Test'
run: ./mvnw ${MAVEN_ARGS} -Djacoco.skip=true install -DskipDistribution=true
linux:
name: 'Linux JDK 11'
runs-on: ubuntu-latest
steps:
- name: 'Checkout'
uses: actions/checkout@v3
- name: 'Set up JDK 11'
uses: actions/setup-java@v3
with:
distribution: 'zulu'
java-version: 11
- name: 'Test'
run: ./mvnw ${MAVEN_ARGS} install
run: ./mvnw ${MAVEN_ARGS} -Djacoco.skip=${{ matrix.java != 21 }} install -DskipDistribution=${{ matrix.java != 21 }}
- name: 'Generate coverage report'
if: matrix.java == 21
run: ./mvnw jacoco:report
- name: 'Upload coverage to Codecov'
if: matrix.java == 21
uses: codecov/codecov-action@v2
- name: 'Publish Snapshots'
if: github.event_name == 'push' && github.ref == 'refs/heads/master' && github.repository == 'mapstruct/mapstruct'
if: matrix.java == 21 && github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository == 'mapstruct/mapstruct'
run: ./mvnw -s etc/ci-settings.xml -DskipTests=true -DskipDistribution=true deploy
linux-jdk-8:
name: 'Linux JDK 8'
integration_test_jdk:
strategy:
fail-fast: false
matrix:
java: [ 8, 11, 17 ]
name: 'Linux JDK ${{ matrix.java }}'
runs-on: ubuntu-latest
steps:
- name: 'Checkout'
uses: actions/checkout@v3
- name: 'Set up JDK 11 for building everything'
uses: actions/setup-java@v3
uses: actions/checkout@v4
- name: 'Set up JDK 21 for building everything'
uses: actions/setup-java@v4
with:
distribution: 'zulu'
java-version: 11
java-version: 21
- name: 'Install Processor'
run: ./mvnw ${MAVEN_ARGS} -DskipTests install -pl processor -am
- name: 'Set up JDK 8 for running integration tests'
uses: actions/setup-java@v3
- name: 'Set up JDK ${{ matrix.java }} for running integration tests'
uses: actions/setup-java@v4
with:
distribution: 'zulu'
java-version: 8
java-version: ${{ matrix.java }}
- name: 'Run integration tests'
run: ./mvnw ${MAVEN_ARGS} verify -pl integrationtest
windows:
name: 'Windows'
runs-on: windows-latest
steps:
- uses: actions/checkout@v3
- name: 'Set up JDK 11'
uses: actions/setup-java@v3
with:
distribution: 'zulu'
java-version: 11
- name: 'Test'
run: ./mvnw %MAVEN_ARGS% install
mac:
name: 'Mac OS'
runs-on: macos-latest
steps:
- uses: actions/checkout@v3
- name: 'Set up JDK 11'
uses: actions/setup-java@v3
with:
distribution: 'zulu'
java-version: 11
- name: 'Test'
run: ./mvnw ${MAVEN_ARGS} install

117
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,117 @@
name: Release
on:
workflow_dispatch:
inputs:
version:
description: 'Release version'
required: true
next:
description: 'Next version'
required: false
jobs:
release:
# This job has been inspired by the moditect release (https://github.com/moditect/moditect/blob/main/.github/workflows/release.yml)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Java
uses: actions/setup-java@v4
with:
java-version: 21
distribution: 'zulu'
cache: maven
- name: Set release version
id: version
run: |
RELEASE_VERSION=${{ github.event.inputs.version }}
NEXT_VERSION=${{ github.event.inputs.next }}
PLAIN_VERSION=`echo ${RELEASE_VERSION} | awk 'match($0, /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)/) { print substr($0, RSTART, RLENGTH); }'`
COMPUTED_NEXT_VERSION="${PLAIN_VERSION}-SNAPSHOT"
if [ -z $NEXT_VERSION ]
then
NEXT_VERSION=$COMPUTED_NEXT_VERSION
fi
./mvnw -ntp -B versions:set versions:commit -DnewVersion=$RELEASE_VERSION -pl :mapstruct-parent -DgenerateBackupPoms=false
git config --global user.email "${{ vars.GH_BOT_EMAIL }}"
git config --global user.name "GitHub Action"
git commit -a -m "Releasing version $RELEASE_VERSION"
git push
echo "RELEASE_VERSION=$RELEASE_VERSION" >> $GITHUB_ENV
echo "NEXT_VERSION=$NEXT_VERSION" >> $GITHUB_ENV
echo "PLAIN_VERSION=$PLAIN_VERSION" >> $GITHUB_ENV
- name: Stage
run: |
export GPG_TTY=$(tty)
./mvnw -ntp -B --file pom.xml \
-Dmaven.site.skip=true -Drelease=true -Ppublication,stage
- name: Release
env:
JRELEASER_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
JRELEASER_GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }}
JRELEASER_GPG_PUBLIC_KEY: ${{ secrets.GPG_PUBLIC_KEY }}
JRELEASER_GPG_SECRET_KEY: ${{ secrets.GPG_PRIVATE_KEY }}
JRELEASER_NEXUS2_MAVEN_CENTRAL_USERNAME: ${{ secrets.SONATYPE_USERNAME }}
JRELEASER_NEXUS2_MAVEN_CENTRAL_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }}
run: |
./mvnw -ntp -B --file pom.xml -pl :mapstruct-parent -Pjreleaser jreleaser:release
- name: JReleaser output
if: always()
uses: actions/upload-artifact@v4
with:
name: jreleaser-release
path: |
parent/target/jreleaser/trace.log
parent/target/jreleaser/output.properties
- name: Reset NEXT_RELEASE_CHANGELOG.md
run: |
echo -e "### Features\n\n### Enhancements\n\n### Bugs\n\n### Documentation\n\n### Build\n" > NEXT_RELEASE_CHANGELOG.md
- name: Set next version
run: |
./mvnw -ntp -B versions:set versions:commit -DnewVersion=${{ env.NEXT_VERSION }} -pl :mapstruct-parent -DgenerateBackupPoms=false
sed -i -e "s@project.build.outputTimestamp>.*</project.build.outputTimestamp@project.build.outputTimestamp>\${git.commit.author.time}</project.build.outputTimestamp@g" parent/pom.xml
git config --global user.email "${{ vars.GH_BOT_EMAIL }}"
git config --global user.name "GitHub Action"
git commit -a -m "Next version ${{ env.NEXT_VERSION }}"
git push
update-website:
# This job has been inspired by the JReleaser update-website job (https://github.com/jreleaser/jreleaser/blob/main/.github/workflows/release.yml)
name: Update Website
needs: [release]
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
repository: mapstruct/mapstruct.org
ref: main
fetch-depth: 0
token: ${{ secrets.GIT_WEBSITE_ACCESS_TOKEN }}
- name: Download assets
shell: bash
run: |
curl -sL https://raw.githubusercontent.com/mapstruct/mapstruct/main/.github/scripts/update-website.sh --output update-website.sh --create-dirs --output-dir tmp
curl -sL "https://github.com/mapstruct/mapstruct/releases/download/${VERSION}/mapstruct-${VERSION}-dist.tar.gz" --output mapstruct-${VERSION}-dist.tar.gz --create-dirs --output-dir tmp
env:
VERSION: ${{ github.event.inputs.version }}
- name: Commit
shell: bash
env:
VERSION: ${{ github.event.inputs.version }}
GH_BOT_EMAIL: ${{ vars.GH_BOT_EMAIL }}
run: |
chmod +x tmp/update-website.sh
tmp/update-website.sh

20
.github/workflows/windows.yml vendored Normal file
View File

@ -0,0 +1,20 @@
name: Windows CI
on: push
env:
MAVEN_ARGS: -V -B --no-transfer-progress -Dhttp.keepAlive=false -Dmaven.wagon.http.pool=false -Dmaven.wagon.httpconnectionManager.ttlSeconds=120
jobs:
windows:
name: 'Windows'
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- name: 'Set up JDK 21'
uses: actions/setup-java@v4
with:
distribution: 'zulu'
java-version: 21
- name: 'Test'
run: ./mvnw %MAVEN_ARGS% install

View File

@ -1,117 +0,0 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

Binary file not shown.

View File

@ -1,2 +1,19 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.2/apache-maven-3.8.2-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
wrapperVersion=3.3.2
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip

View File

@ -1,9 +0,0 @@
- [ ] Is this an issue (and hence not a question)?
If this is a question how to use MapStruct there are several resources available.
- Our reference- and API [documentation](http://mapstruct.org/documentation/reference-guide/).
- Our [examples](https://github.com/mapstruct/mapstruct-examples) repository (contributions always welcome)
- Our [FAQ](http://mapstruct.org/faq/)
- [StackOverflow](https://stackoverflow.com), tag MapStruct
- [Gitter](https://gitter.im/mapstruct/mapstruct-users) (you usually get fast feedback)
- Our [google group](https://groups.google.com/forum/#!forum/mapstruct-users)

29
NEXT_RELEASE_CHANGELOG.md Normal file
View File

@ -0,0 +1,29 @@
### Features
* Support for Java 21 Sequenced Collections (#3240)
### Enhancements
* Add support for locale parameter for numberFormat and dateFormat (#3628)
* Detect Builder without a factory method (#3729) - With this if there is an inner class that ends with `Builder` and has a constructor with parameters,
it will be treated as a potential builder.
Builders through static methods on the type have a precedence.
* Behaviour change: Warning when the target has no target properties (#1140)
### Bugs
* Improve error message when mapping non-iterable to array (#3786)
### Documentation
### Build
### Behaviour Change
#### Warning when the target has no target properties
With this change, if the target bean does not have any target properties, a warning will be shown.
This is like this to avoid potential mistakes by users, where they might think that the target bean has properties, but it does not.

View File

@ -12,7 +12,7 @@
<parent>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-parent</artifactId>
<version>1.6.0-SNAPSHOT</version>
<version>1.7.0-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>

View File

@ -29,7 +29,9 @@
<!-- See http://checkstyle.sf.net/config_misc.html#Translation -->
<module name="Translation"/>
<module name="FileLength"/>
<module name="FileLength">
<property name="max" value="2500"/>
</module>
<module name="LineLength">
<property name="max" value="120"/>
@ -144,7 +146,9 @@
</module>
<module name="TypecastParenPad"/>
<module name="WhitespaceAfter"/>
<module name="WhitespaceAround"/>
<module name="WhitespaceAround">
<property name="ignoreEnhancedForColon" value="false"/>
</module>
<module name="EmptyLineSeparator">
<property name="tokens" value="IMPORT, CLASS_DEF, INTERFACE_DEF, STATIC_INIT, INSTANCE_INIT, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>

View File

@ -42,8 +42,10 @@ Kevin Grüneberg - https://github.com/kevcodez
Lukas Lazar - https://github.com/LukeLaz
Nikolas Charalambidis - https://github.com/Nikolas-Charalambidis
Michael Pardo - https://github.com/pardom
Muhammad Usama - https://github.com/the-mgi
Mustafa Caylak - https://github.com/luxmeter
Oliver Ehrenmüller - https://github.com/greuelpirat
Oliver Erhart - https://github.com/thunderhook
Paul Strugnell - https://github.com/ps-powa
Pascal Grün - https://github.com/pascalgn
Pavel Makhov - https://github.com/streetturtle
@ -67,3 +69,5 @@ Timo Eckhardt - https://github.com/timoe
Tomek Gubala - https://github.com/vgtworld
Valentin Kulesh - https://github.com/unshare
Vincent Alexander Beelte - https://github.com/grandmasterpixel
Winter Andreas - https://github.dev/wandi34
Xiu Hong Kooi - https://github.com/kooixh

View File

@ -12,7 +12,7 @@
<parent>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-parent</artifactId>
<version>1.6.0-SNAPSHOT</version>
<version>1.7.0-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>

View File

@ -12,7 +12,7 @@
<parent>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-parent</artifactId>
<version>1.6.0-SNAPSHOT</version>
<version>1.7.0-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>

View File

@ -0,0 +1,176 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct;
import java.lang.annotation.Annotation;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.CLASS;
/**
* This can be used to have mapstruct generate additional annotations on classes/methods.
* <p>
* Examples based on the spring framework annotations.
* </p>
* Marking a class as `Lazy`:
*
* <pre><code>
* &#64;AnnotateWith( value = Lazy.class )
* &#64;Mapper
* public interface FooMapper {
* // mapper code
* }
* </code></pre>
*
* The following code would be generated:
*
* <pre><code>
* &#64;Lazy
* public class FooMapperImpl implements FooMapper {
* // mapper code
* }
* </code></pre>
* Setting the profile on the generated implementation:
*
* <pre><code>
* &#64;AnnotateWith( value = Profile.class, elements = @AnnotateWith.Element( strings = "prod" ) )
* &#64;Mapper
* public interface FooMapper {
* // mapper code
* }
* </code></pre>
*
* The following code would be generated:
*
* <pre><code>
* &#64;Profile( value = "prod" )
* public class FooMapperImpl implements FooMapper {
* // mapper code
* }
* </code></pre>
*
* @author Ben Zegveld
* @since 1.6
*/
@Repeatable( AnnotateWiths.class )
@Retention( CLASS )
@Target( { TYPE, METHOD, ANNOTATION_TYPE } )
public @interface AnnotateWith {
/**
* @return the annotation class that needs to be added.
*/
Class<? extends Annotation> value();
/**
* @return the annotation elements that are to be applied to this annotation.
*/
Element[] elements() default {};
/**
* Used in combination with {@link AnnotateWith} to configure the annotation elements. Only 1 value type may be used
* within the same annotation at a time. For example mixing shorts and ints is not allowed.
*
* @author Ben Zegveld
* @since 1.6
*/
@interface Element {
/**
* @return name of the annotation element.
*/
String name() default "value";
/**
* cannot be used in conjunction with other value fields.
*
* @return short value(s) for the annotation element.
*/
short[] shorts() default {};
/**
* cannot be used in conjunction with other value fields.
*
* @return byte value(s) for the annotation element.
*/
byte[] bytes() default {};
/**
* cannot be used in conjunction with other value fields.
*
* @return int value(s) for the annotation element.
*/
int[] ints() default {};
/**
* cannot be used in conjunction with other value fields.
*
* @return long value(s) for the annotation element.
*/
long[] longs() default {};
/**
* cannot be used in conjunction with other value fields.
*
* @return float value(s) for the annotation element.
*/
float[] floats() default {};
/**
* cannot be used in conjunction with other value fields.
*
* @return double value(s) for the annotation element.
*/
double[] doubles() default {};
/**
* cannot be used in conjunction with other value fields.
*
* @return char value(s) for the annotation element.
*/
char[] chars() default {};
/**
* cannot be used in conjunction with other value fields.
*
* @return boolean value(s) for the annotation element.
*/
boolean[] booleans() default {};
/**
* cannot be used in conjunction with other value fields.
*
* @return string value(s) for the annotation element.
*/
String[] strings() default {};
/**
* cannot be used in conjunction with other value fields.
*
* @return class value(s) for the annotation element.
*/
Class<?>[] classes() default {};
/**
* only used in conjunction with the {@link #enums()} annotation element.
*
* @return the class of the enum.
*/
Class<? extends Enum<?>> enumClass() default NullEnum.class;
/**
* cannot be used in conjunction with other value fields. {@link #enumClass()} is also required when using
* {@link #enums()}
*
* @return enum value(s) for the annotation element.
*/
String[] enums() default {};
}
}

View File

@ -0,0 +1,31 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.CLASS;
/**
* This can be used to have mapstruct generate additional annotations on classes/methods.
*
* @author Ben Zegveld
* @since 1.6
*/
@Retention( CLASS )
@Target( { TYPE, METHOD } )
public @interface AnnotateWiths {
/**
* The configuration of the additional annotations.
*
* @return The configuration of the additional annotations.
*/
AnnotateWith[] value();
}

View File

@ -19,6 +19,8 @@ import static org.mapstruct.SubclassExhaustiveStrategy.COMPILE_ERROR;
/**
* Configures the mapping between two bean types.
* <p>
* Unless otherwise specified these properties are inherited to the generated bean mapping methods.
* <p>
* Either {@link #resultType()}, {@link #qualifiedBy()} or {@link #nullValueMappingStrategy()} must be specified.
* </p>
* <p><strong>Example:</strong> Determining the result type</p>
@ -58,6 +60,8 @@ public @interface BeanMapping {
/**
* Specifies the result type of the factory method to be used in case several factory methods qualify.
* <p>
* <b>NOTE</b>: This property is not inherited to generated mapping methods
*
* @return the resultType to select
*/
@ -128,6 +132,18 @@ public @interface BeanMapping {
*/
SubclassExhaustiveStrategy subclassExhaustiveStrategy() default COMPILE_ERROR;
/**
* Specifies the exception type to be thrown when a missing subclass implementation is detected
* in combination with {@link SubclassMappings}, based on the {@link #subclassExhaustiveStrategy()}.
* <p>
* This exception will only be thrown when the {@code subclassExhaustiveStrategy} is set to
* {@link SubclassExhaustiveStrategy#RUNTIME_EXCEPTION}.
*
* @return the exception class to throw when missing implementations are found.
* Defaults to {@link IllegalArgumentException}.
*/
Class<? extends Exception> subclassExhaustiveException() default IllegalArgumentException.class;
/**
* Default ignore all mappings. All mappings have to be defined manually. No automatic mapping will take place. No
* warning will be issued on missing source or target properties.
@ -145,6 +161,8 @@ public @interface BeanMapping {
* source properties report.
* <p>
* <b>NOTE</b>: This does not support ignoring nested source properties
* <p>
* <b>NOTE</b>: This property is not inherited to generated mapping methods
*
* @return The source properties that should be ignored when performing a report
*
@ -152,6 +170,17 @@ public @interface BeanMapping {
*/
String[] ignoreUnmappedSourceProperties() default {};
/**
* How unmapped properties of the source type of a mapping should be reported.
* If no policy is configured, the policy given via {@link MapperConfig#unmappedSourcePolicy()} or
* {@link Mapper#unmappedSourcePolicy()} will be applied, using {@link ReportingPolicy#IGNORE} by default.
*
* @return The reporting policy for unmapped source properties.
*
* @since 1.6
*/
ReportingPolicy unmappedSourcePolicy() default ReportingPolicy.IGNORE;
/**
* How unmapped properties of the target type of a mapping should be reported.
* If no policy is configured, the policy given via {@link MapperConfig#unmappedTargetPolicy()} or

View File

@ -7,6 +7,54 @@ package org.mapstruct;
/**
* Strategy for propagating the value of collection-typed properties from source to target.
* <p>
* In the table below, the dash {@code -} indicates a property name.
* Next, the trailing {@code s} indicates the plural form.
* The table explains the options and how they are applied to the presence / absence of a
* {@code set-s}, {@code add-} and / or {@code get-s} method on the target object.
* <table>
* <caption>Collection mapping strategy options</caption>
* <tr>
* <th>Option</th>
* <th>Only target set-s Available</th>
* <th>Only target add- Available</th>
* <th>Both set-s/add- Available</th>
* <th>No set-s/add- Available</th>
* <th>Existing Target ({@code @TargetType})</th>
* </tr>
* <tr>
* <td>{@link #ACCESSOR_ONLY}</td>
* <td>set-s</td>
* <td>get-s</td>
* <td>set-s</td>
* <td>get-s</td>
* <td>get-s</td>
* </tr>
* <tr>
* <td>{@link #SETTER_PREFERRED}</td>
* <td>set-s</td>
* <td>add-</td>
* <td>set-s</td>
* <td>get-s</td>
* <td>get-s</td>
* </tr>
* <tr>
* <td>{@link #ADDER_PREFERRED}</td>
* <td>set-s</td>
* <td>add-</td>
* <td>add-</td>
* <td>get-s</td>
* <td>get-s</td>
* </tr>
* <tr>
* <td>{@link #TARGET_IMMUTABLE}</td>
* <td>set-s</td>
* <td>exception</td>
* <td>set-s</td>
* <td>exception</td>
* <td>set-s</td>
* </tr>
* </table>
*
* @author Sjaak Derksen
*/

View File

@ -11,24 +11,35 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation marks a method as a <em>presence check method</em> to check check for presence in beans.
* This annotation marks a method as a <em>presence check method</em> to check for presence in beans
* or it can be used to define additional check methods for something like source parameters.
* <p>
* By default bean properties are checked against {@code null} or using a presence check method in the source bean.
* By default, bean properties are checked against {@code null} or using a presence check method in the source bean.
* If a presence check method is available then it will be used instead.
* <p>
* Presence check methods have to return {@code boolean}.
* The following parameters are accepted for the presence check methods:
* <ul>
* <li>The parameter with the value of the source property.
* e.g. the value given by calling {@code getName()} for the name property of the source bean</li>
* e.g. the value given by calling {@code getName()} for the name property of the source bean
* - only possible when using the {@link ConditionStrategy#PROPERTIES}
* </li>
* <li>The mapping source parameter</li>
* <li>{@code @}{@link Context} parameter</li>
* <li>
* {@code @}{@link TargetPropertyName} parameter -
* only possible when using the {@link ConditionStrategy#PROPERTIES}
* </li>
* <li>
* {@code @}{@link SourcePropertyName} parameter -
* only possible when using the {@link ConditionStrategy#PROPERTIES}
* </li>
* </ul>
*
* <strong>Note:</strong> The usage of this annotation is <em>mandatory</em>
* for a method to be considered as a presence check method.
*
* <pre><code>
* <pre><code class='java'>
* public class PresenceCheckUtils {
*
* &#64;Condition
@ -43,11 +54,10 @@ import java.lang.annotation.Target;
* MovieDto map(Movie movie);
* }
* </code></pre>
*
* <p>
* The following implementation of {@code MovieMapper} will be generated:
*
* <pre>
* <code>
* <pre><code class='java'>
* public class MovieMapperImpl implements MovieMapper {
*
* &#64;Override
@ -65,14 +75,22 @@ import java.lang.annotation.Target;
* return movieDto;
* }
* }
* </code>
* </pre>
* </code></pre>
* <p>
* This annotation can also be used as a meta-annotation to define the condition strategy.
*
* @author Filip Hrisafov
* @see SourceParameterCondition
* @since 1.5
*/
@Target({ ElementType.METHOD })
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.CLASS)
public @interface Condition {
/**
* @return the places where the condition should apply to
* @since 1.6
*/
ConditionStrategy[] appliesTo() default ConditionStrategy.PROPERTIES;
}

View File

@ -0,0 +1,23 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct;
/**
* Strategy for defining what to what a condition (check) method is applied to
*
* @author Filip Hrisafov
* @since 1.6
*/
public enum ConditionStrategy {
/**
* The condition method should be applied whether a property should be mapped.
*/
PROPERTIES,
/**
* The condition method should be applied to check if a source parameters should be mapped.
*/
SOURCE_PARAMETERS,
}

View File

@ -98,7 +98,7 @@ public @interface EnumMapping {
* <ul>
* <li>{@link MappingConstants#SUFFIX_TRANSFORMATION} - applies the given {@link #configuration()} as a
* suffix to the source enum</li>
* <li>{@link MappingConstants#STRIP_SUFFIX_TRANSFORMATION} - strips the the given {@link #configuration()}
* <li>{@link MappingConstants#STRIP_SUFFIX_TRANSFORMATION} - strips the given {@link #configuration()}
* from the end of the source enum</li>
* <li>{@link MappingConstants#PREFIX_TRANSFORMATION} - applies the given {@link #configuration()} as a
* prefix to the source enum</li>

View File

@ -0,0 +1,67 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Configures the ignored of one bean attribute.
*
* <p>
* The name all attributes of for ignored is to be specified via {@link #targets()}.
* </p>
*
* <p>
* <strong>Example 1:</strong> Implicitly mapping fields with the same name:
* </p>
*
* <pre><code class='java'>
* // We need ignored Human.name and Human.lastName
* // we can use &#64;Ignored with parameters "name", "lastName" {@link #targets()}
* &#64;Mapper
* public interface HumanMapper {
* &#64;Ignored( targets = { "name", "lastName" } )
* HumanDto toHumanDto(Human human)
* }
* </code></pre>
* <pre><code class='java'>
* // generates:
* &#64;Override
* public HumanDto toHumanDto(Human human) {
* humanDto.setFullName( human.getFullName() );
* // ...
* }
* </code></pre>
*
* @author Ivashin Aleksey
*/
@Repeatable(IgnoredList.class)
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
public @interface Ignored {
/**
* Whether the specified properties should be ignored by the generated mapping method.
* This can be useful when certain attributes should not be propagated from source to target or when properties in
* the target object are populated using a decorator and thus would be reported as unmapped target property by
* default.
*
* @return The target names of the configured properties that should be ignored
*/
String[] targets();
/**
* The prefix that should be applied to all the properties specified via {@link #targets()}.
*
* @return The target prefix to be applied to the defined properties
*/
String prefix() default "";
}

View File

@ -0,0 +1,54 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Configures the ignored list for several bean attributes.
* <p>
* <strong>TIP: When using Java 8 or later, you can omit the {@code @IgnoredList}
* wrapper annotation and directly specify several {@code @Ignored} annotations on one method.</strong>
*
* <p>These two examples are equal.
* </p>
* <pre><code class='java'>
* // before Java 8
* &#64;Mapper
* public interface MyMapper {
* &#64;IgnoredList({
* &#64;Ignored(targets = { "firstProperty" } ),
* &#64;Ignored(targets = { "secondProperty" } )
* })
* HumanDto toHumanDto(Human human);
* }
* </code></pre>
* <pre><code class='java'>
* // Java 8 and later
* &#64;Mapper
* public interface MyMapper {
* &#64;Ignored(targets = { "firstProperty" } ),
* &#64;Ignored(targets = { "secondProperty" } )
* HumanDto toHumanDto(Human human);
* }
* </code></pre>
*
* @author Ivashin Aleksey
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE })
public @interface IgnoredList {
/**
* The configuration of the bean attributes.
*
* @return The configuration of the bean attributes.
*/
Ignored[] value();
}

View File

@ -81,8 +81,8 @@ import java.lang.annotation.Target;
public @interface InheritInverseConfiguration {
/**
* The name of the inverse mapping method to inherit the mappings from. Needs only to be specified in case more than
* one inverse method with matching source and target type exists.
* The name of the inverse mapping method to inherit the mappings from. Needs to be specified only in case more than
* one inverse method exists with a matching source and target type exists.
*
* @return The name of the inverse mapping method to inherit the mappings from.
*/

View File

@ -10,6 +10,7 @@ package org.mapstruct;
* JSR330 / Jakarta.
*
* @author Kevin Grüneberg
* @author Lucas Resch
*/
public enum InjectionStrategy {
@ -17,5 +18,8 @@ public enum InjectionStrategy {
FIELD,
/** Annotations are written on the constructor **/
CONSTRUCTOR
CONSTRUCTOR,
/** A dedicated setter method is created */
SETTER
}

View File

@ -66,19 +66,38 @@ public @interface IterableMapping {
/**
* A format string as processable by {@link SimpleDateFormat} if the annotated method maps from an iterable of
* {@code String} to an iterable {@link Date} or vice-versa. Will be ignored for all other element types.
* <p>
* If the {@link #locale()} is also specified, the format will consider the specified locale when processing
* the date. Otherwise, the system's default locale will be used.
*
* @return A date format string as processable by {@link SimpleDateFormat}.
* @see #locale()
*/
String dateFormat() default "";
/**
* A format string as processable by {@link DecimalFormat} if the annotated method maps from a
* {@link Number} to a {@link String} or vice-versa. Will be ignored for all other element types.
* <p>
* If the {@link #locale()} is also specified, the number format will be applied in the context of the given locale.
* Otherwise, the system's default locale will be used to process the number format.
*
* @return A decimal format string as processable by {@link DecimalFormat}.
* @see #locale()
*/
String numberFormat() default "";
/**
* Specifies the locale to be used when processing {@link #dateFormat()} or {@link #numberFormat()}.
* <p>
* The locale should be a plain tag representing the language, such as "en" for English, "de" for German, etc.
* <p>
* If no locale is specified, the system's default locale will be used.
*
* @return A string representing the locale to be used when formatting dates or numbers.
*/
String locale() default "";
/**
* A qualifier can be specified to aid the selection process of a suitable mapper. This is useful in case multiple
* mappers (hand written of internal) qualify and result in an 'Ambiguous mapping methods found' error.

View File

@ -0,0 +1,115 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Allows the definition of Javadoc comments in the MapStruct <code>Mapper</code> generated class.
*
* <p>The annotation provides support for the usual Javadoc comments elements by defining analogous attributes.</p>
*
*
* <p>Please, note that at least one of these attributes must be specified.</p>
*
* <p>
* For instance, the following definition;
* </p>
* <pre><code class='java'>
* &#64;Javadoc(
* value = "This is the description",
* authors = { "author1", "author2" },
* deprecated = "Use {&#64;link OtherMapper} instead",
* since = "0.1"
* )
* </code></pre>
*
* <p>
* will generate:
* </p>
*
* <pre><code class='java'>
* /**
* * This is the description
* *
* * &#64;author author1
* * &#64;author author2
* *
* * &#64;deprecated Use {&#64;link OtherMapper} instead
* * &#64;since 0.1
* *&#47;
* </code></pre>
*
* <p>
* The entire Javadoc comment block can be passed directly:
* </p>
* <pre><code class='java'>
* &#64;Javadoc("This is the description\n"
* + "\n"
* + "&#64;author author1\n"
* + "&#64;author author2\n"
* + "\n"
* + "&#64;deprecated Use {&#64;link OtherMapper} instead\n"
* + "&#64;since 0.1\n"
* )
* </code></pre>
*
* <pre><code class='java'>
* // or using Text Blocks
* &#64;Javadoc(
* """
* This is the description
*
* &#64;author author1
* &#64;author author2
*
* &#64;deprecated Use {&#64;link OtherMapper} instead
* &#64;since 0.1
* """
* )
* </code></pre>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface Javadoc {
/**
* Main Javadoc comment text block.
*
* @return Main Javadoc comment text block.
*/
String value() default "";
/**
* List of authors of the code that it is being documented.
* <p>
* It will generate a list of the Javadoc tool comment element <code>&#64;author</code>
* with the different values and in the order provided.
*
* @return array of javadoc authors.
*/
String[] authors() default { };
/**
* Specifies that the functionality that is being documented is deprecated.
* <p>
* Corresponds to the <code>&#64;deprecated</code> Javadoc tool comment element.
*
* @return Deprecation message about the documented functionality
*/
String deprecated() default "";
/**
* Specifies the version since the functionality that is being documented is available.
* <p>
* Corresponds to the <code>&#64;since</code> Javadoc tool comment element.
*
* @return Version since the functionality is available
*/
String since() default "";
}

View File

@ -56,8 +56,12 @@ public @interface MapMapping {
/**
* A format string as processable by {@link SimpleDateFormat} if the annotated method maps from a map with key type
* {@code String} to an map with key type {@link Date} or vice-versa. Will be ignored for all other key types.
* <p>
* If the {@link #locale()} is specified, the format will consider the specified locale when processing the date.
* Otherwise, the system's default locale will be used.
*
* @return A date format string as processable by {@link SimpleDateFormat}.
* @see #locale()
*/
String keyDateFormat() default "";
@ -65,27 +69,50 @@ public @interface MapMapping {
* A format string as processable by {@link SimpleDateFormat} if the annotated method maps from a map with value
* type {@code String} to an map with value type {@link Date} or vice-versa. Will be ignored for all other value
* types.
* <p>
* If the {@link #locale()} is specified, the format will consider the specified locale when processing the date.
* Otherwise, the system's default locale will be used.
*
* @return A date format string as processable by {@link SimpleDateFormat}.
* @see #locale()
*/
String valueDateFormat() default "";
/**
* A format string as processable by {@link DecimalFormat} if the annotated method maps from a
* {@link Number} to a {@link String} or vice-versa. Will be ignored for all other key types.
* <p>
* If the {@link #locale()} is specified, the number format will be applied in the context of the given locale.
* Otherwise, the system's default locale will be used.
*
* @return A decimal format string as processable by {@link DecimalFormat}.
* @see #locale()
*/
String keyNumberFormat() default "";
/**
* A format string as processable by {@link DecimalFormat} if the annotated method maps from a
* {@link Number} to a {@link String} or vice-versa. Will be ignored for all other value types.
* <p>
* If the {@link #locale()} is specified, the number format will be applied in the context of the given locale.
* Otherwise, the system's default locale will be used.
*
* @return A decimal format string as processable by {@link DecimalFormat}.
* @see #locale()
*/
String valueNumberFormat() default "";
/**
* Specifies the locale to be used when processing {@link SimpleDateFormat} or {@link DecimalFormat} for key or
* value mappings in maps. The locale should be a plain tag representing the language, such as "en" for English,
* "de" for German, etc.
* <p>
* If no locale is specified, the system's default locale will be used.
*
* @return A string representing the locale to be used when formatting dates or numbers in maps.
*/
String locale() default "";
/**
* A key value qualifier can be specified to aid the selection process of a suitable mapper. This is useful in
* case multiple mappers (hand written of internal) qualify and result in an 'Ambiguous mapping methods found'

View File

@ -74,6 +74,7 @@ import static org.mapstruct.SubclassExhaustiveStrategy.COMPILE_ERROR;
* </code></pre>
*
* @author Gunnar Morling
* @see Javadoc
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
@ -280,6 +281,18 @@ public @interface Mapper {
*/
SubclassExhaustiveStrategy subclassExhaustiveStrategy() default COMPILE_ERROR;
/**
* Specifies the exception type to be thrown when a missing subclass implementation is detected
* in combination with {@link SubclassMappings}, based on the {@link #subclassExhaustiveStrategy()}.
* <p>
* This exception will only be thrown when the {@code subclassExhaustiveStrategy} is set to
* {@link SubclassExhaustiveStrategy#RUNTIME_EXCEPTION}.
*
* @return the exception class to throw when missing implementations are found.
* Defaults to {@link IllegalArgumentException}.
*/
Class<? extends Exception> subclassExhaustiveException() default IllegalArgumentException.class;
/**
* Determines whether to use field or constructor injection. This is only used on annotated based component models
* such as CDI, Spring and JSR 330.
@ -298,7 +311,7 @@ public @interface Mapper {
* Can be configured by the {@link MapperConfig#disableSubMappingMethodsGeneration()} as well.
* <p>
* Note: If you need to use {@code disableSubMappingMethodsGeneration} please contact the MapStruct team at
* <a href="http://mapstruct.org">mapstruct.org</a> or
* <a href="https://mapstruct.org">mapstruct.org</a> or
* <a href="https://github.com/mapstruct/mapstruct">github.com/mapstruct/mapstruct</a> to share what problem you
* are facing with the automatic sub-mapping generation.
*

View File

@ -249,6 +249,18 @@ public @interface MapperConfig {
*/
SubclassExhaustiveStrategy subclassExhaustiveStrategy() default COMPILE_ERROR;
/**
* Specifies the exception type to be thrown when a missing subclass implementation is detected
* in combination with {@link SubclassMappings}, based on the {@link #subclassExhaustiveStrategy()}.
* <p>
* This exception will only be thrown when the {@code subclassExhaustiveStrategy} is set to
* {@link SubclassExhaustiveStrategy#RUNTIME_EXCEPTION}.
*
* @return the exception class to throw when missing implementations are found.
* Defaults to {@link IllegalArgumentException}.
*/
Class<? extends Exception> subclassExhaustiveException() default IllegalArgumentException.class;
/**
* Determines whether to use field or constructor injection. This is only used on annotated based component models
* such as CDI, Spring and JSR 330.
@ -269,7 +281,7 @@ public @interface MapperConfig {
* Can be overridden by {@link Mapper#disableSubMappingMethodsGeneration()}
* <p>
* Note: If you need to use {@code disableSubMappingMethodsGeneration} please contact the MapStruct team at
* <a href="http://mapstruct.org">mapstruct.org</a> or
* <a href="https://mapstruct.org">mapstruct.org</a> or
* <a href="https://github.com/mapstruct/mapstruct">github.com/mapstruct/mapstruct</a> to share what problem you
* are facing with the automatic sub-mapping generation.
*

View File

@ -20,7 +20,7 @@ import org.mapstruct.control.MappingControl;
import static org.mapstruct.NullValueCheckStrategy.ON_IMPLICIT_CONVERSION;
/**
* Configures the mapping of one bean attribute or enum constant.
* Configures the mapping of one bean attribute.
* <p>
* The name of the mapped attribute or constant is to be specified via {@link #target()}. For mapped bean attributes it
* is assumed by default that the attribute has the same name in the source bean. Alternatively, one of
@ -136,9 +136,6 @@ import static org.mapstruct.NullValueCheckStrategy.ON_IMPLICIT_CONVERSION;
* }
* </code></pre>
*
* <b>IMPORTANT NOTE:</b> the enum mapping capability is deprecated and replaced by {@link ValueMapping} it
* will be removed in subsequent versions.
*
* @author Gunnar Morling
*/
@ -178,19 +175,38 @@ public @interface Mapping {
/**
* A format string as processable by {@link SimpleDateFormat} if the attribute is mapped from {@code String} to
* {@link Date} or vice-versa. Will be ignored for all other attribute types and when mapping enum constants.
* <p>
* If the {@link #locale()} is also specified, the format will consider the specified locale when processing
* the date. Otherwise, the system's default locale will be used.
*
* @return A date format string as processable by {@link SimpleDateFormat}.
* @see #locale()
*/
String dateFormat() default "";
/**
* A format string as processable by {@link DecimalFormat} if the annotated method maps from a
* {@link Number} to a {@link String} or vice-versa. Will be ignored for all other element types.
* <p>
* If the {@link #locale()} is also specified, the number format will be applied in the context of the given locale.
* Otherwise, the system's default locale will be used to process the number format.
*
* @return A decimal format string as processable by {@link DecimalFormat}.
* @see #locale()
*/
String numberFormat() default "";
/**
* Specifies the locale to be used when processing {@link #dateFormat()} or {@link #numberFormat()}.
* <p>
* The locale should be a plain tag representing the language, such as "en" for English, "de" for German, etc.
* <p>
* If no locale is specified, the system's default locale will be used.
*
* @return A string representing the locale to be used when formatting dates or numbers.
*/
String locale() default "";
/**
* A constant {@link String} based on which the specified target property is to be set.
* <p>
@ -287,9 +303,12 @@ public @interface Mapping {
/**
* Whether the property specified via {@link #target()} should be ignored by the generated mapping method or not.
* This can be useful when certain attributes should not be propagated from source or target or when properties in
* This can be useful when certain attributes should not be propagated from source to target or when properties in
* the target object are populated using a decorator and thus would be reported as unmapped target property by
* default.
* <p>
* If you have multiple properties to ignore,
* you can use the {@link Ignored} annotation instead and group them all at once.
*
* @return {@code true} if the given property should be ignored, {@code false} otherwise
*/

View File

@ -109,7 +109,12 @@ public final class MappingConstants {
public static final String DEFAULT = "default";
/**
* The generated mapper is an application-scoped CDI bean and can be retrieved via @Inject
* The generated mapper is an application-scoped CDI bean and can be retrieved via @Inject.
* The annotations are either from {@code javax} or {@code jakarta}.
* Priority have the {@code javax} annotations.
* In case you want to only use Jakarta then use {@link #JAKARTA_CDI}.
*
* @see #JAKARTA_CDI
*/
public static final String CDI = "cdi";
@ -138,6 +143,12 @@ public final class MappingConstants {
*/
public static final String JAKARTA = "jakarta";
/**
* The generated mapper is an application-scoped Jakarta CDI bean and can be retrieved via @Inject.
* @see #CDI
*/
public static final String JAKARTA_CDI = "jakarta-cdi";
}
}

View File

@ -0,0 +1,15 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct;
/**
* To be used as a default value for enum class annotation elements.
*
* @author Ben Zegveld
* @since 1.6
*/
enum NullEnum {
}

View File

@ -8,7 +8,7 @@ package org.mapstruct;
/**
* Strategy for dealing with null source values.
*
* <b>Note:</b> This strategy is not in effect when the a specific source presence check method is defined
* <b>Note:</b> This strategy is not in effect when a specific source presence check method is defined
* in the service provider interface (SPI).
* <p>
* <b>Note</b>: some types of mappings (collections, maps), in which MapStruct is instructed to use a getter or adder

View File

@ -10,7 +10,7 @@ package org.mapstruct;
* {@link NullValuePropertyMappingStrategy} can be defined on {@link MapperConfig}, {@link Mapper}, {@link BeanMapping}
* and {@link Mapping}.
* Precedence is arranged in the reverse order. So {@link Mapping} will override {@link BeanMapping}, will
* overide {@link Mapper}
* override {@link Mapper}
*
* The enum <b>only applies to update methods</b>: methods that update a pre-existing target (annotated with
* {@code @}{@link MappingTarget}).

View File

@ -21,6 +21,7 @@ import java.lang.annotation.Target;
* <li>{@link IterableMapping#qualifiedBy() }</li>
* <li>{@link MapMapping#keyQualifiedBy() }</li>
* <li>{@link MapMapping#valueQualifiedBy() }</li>
* <li>{@link SubclassMapping#qualifiedBy() }</li>
* </ul>
* <p><strong>Example:</strong></p>
* <pre><code class='java'>

View File

@ -0,0 +1,74 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation marks a method as a <em>check method</em> to check if a source parameter needs to be mapped.
* <p>
* By default, source parameters are checked against {@code null}, unless they are primitives.
* <p>
* Check methods have to return {@code boolean}.
* The following parameters are accepted for the presence check methods:
* <ul>
* <li>The mapping source parameter</li>
* <li>{@code @}{@link Context} parameter</li>
* </ul>
*
* <strong>Note:</strong> The usage of this annotation is <em>mandatory</em>
* for a method to be considered as a source check method.
*
* <pre><code class='java'>
* public class PresenceCheckUtils {
*
* &#64;SourceParameterCondition
* public static boolean isDefined(Car car) {
* return car != null &#38;&#38; car.getId() != null;
* }
* }
*
* &#64;Mapper(uses = PresenceCheckUtils.class)
* public interface CarMapper {
*
* CarDto map(Car car);
* }
* </code></pre>
*
* The following implementation of {@code CarMapper} will be generated:
*
* <pre><code class='java'>
* public class CarMapperImpl implements CarMapper {
*
* &#64;Override
* public CarDto map(Car car) {
* if ( !PresenceCheckUtils.isDefined( car ) ) {
* return null;
* }
*
* CarDto carDto = new CarDto();
*
* carDto.setId( car.getId() );
* // ...
*
* return carDto;
* }
* }
* </code></pre>
*
* @author Filip Hrisafov
* @since 1.6
* @see Condition @Condition
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.CLASS)
@Condition(appliesTo = ConditionStrategy.SOURCE_PARAMETERS)
public @interface SourceParameterCondition {
}

View File

@ -0,0 +1,26 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation marks a <em>presence check method</em> parameter as a source property name parameter.
* <p>
* This parameter enables conditional filtering based on source property name at run-time.
* Parameter must be of type {@link String} and can be present only in {@link Condition} method.
* </p>
*
* @author Oliver Erhart
* @since 1.6
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.CLASS)
public @interface SourcePropertyName {
}

View File

@ -5,6 +5,7 @@
*/
package org.mapstruct;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
@ -48,7 +49,7 @@ import org.mapstruct.util.Experimental;
* }
* </code></pre>
* <strong>Example 2:</strong> For parents that can be created. (e.g. normal classes or interfaces with
* &#64;Mappper( uses = ObjectFactory.class ) )
* &#64;Mapper( uses = ObjectFactory.class ) )
* <pre><code class='java'>
* // generates
* &#64;Override
@ -81,4 +82,29 @@ public @interface SubclassMapping {
* @return the target subclass to map the source to.
*/
Class<?> target();
/**
* A qualifier can be specified to aid the selection process of a suitable mapper. This is useful in case multiple
* mapping methods (hand written or generated) qualify and thus would result in an 'Ambiguous mapping methods found'
* error. A qualifier is a custom annotation and can be placed on a hand written mapper class or a method.
*
* @return the qualifiers
* @see Qualifier
*/
Class<? extends Annotation>[] qualifiedBy() default {};
/**
* String-based form of qualifiers; When looking for a suitable mapping method for a given property, MapStruct will
* only consider those methods carrying directly or indirectly (i.e. on the class-level) a {@link Named} annotation
* for each of the specified qualifier names.
* <p>
* Note that annotation-based qualifiers are generally preferable as they allow more easily to find references and
* are safe for refactorings, but name-based qualifiers can be a less verbose alternative when requiring a large
* number of qualifiers as no custom annotation types are needed.
*
* @return One or more qualifier name(s)
* @see #qualifiedBy()
* @see Named
*/
String[] qualifiedByName() default {};
}

View File

@ -45,7 +45,7 @@ import org.mapstruct.util.Experimental;
* @author Ben Zegveld
* @since 1.5
*/
@Target(ElementType.METHOD)
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.CLASS)
@Experimental
public @interface SubclassMappings {

View File

@ -0,0 +1,25 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation marks a <em>presence check method</em> parameter as a target property name parameter.
* <p>
* This parameter enables conditional filtering based on target property name at run-time.
* Parameter must be of type {@link String} and can be present only in {@link Condition} method.
* </p>
* @author Nikola Ivačič
* @since 1.6
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.CLASS)
public @interface TargetPropertyName {
}

View File

@ -84,7 +84,7 @@ import java.lang.annotation.Target;
*/
@Repeatable(ValueMappings.class)
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
public @interface ValueMapping {
/**
* The source value constant to use for this mapping.

View File

@ -40,7 +40,7 @@ import java.lang.annotation.Target;
*
* @author Sjaak Derksen
*/
@Target(ElementType.METHOD)
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.CLASS)
public @interface ValueMappings {

View File

@ -13,6 +13,6 @@
* This package contains several annotations which allow to configure how mapper interfaces are generated.
* </p>
*
* @see <a href="http://mapstruct.org/">MapStruct reference documentation</a>
* @see <a href="https://mapstruct.org/">MapStruct reference documentation</a>
*/
package org.mapstruct;

View File

@ -12,7 +12,7 @@
<parent>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-parent</artifactId>
<version>1.6.0-SNAPSHOT</version>
<version>1.7.0-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>
@ -39,6 +39,13 @@
<groupId>org.mapstruct.tools.gem</groupId>
<artifactId>gem-api</artifactId>
</dependency>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
</dependencies>
<build>
@ -59,7 +66,7 @@
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<outputDirectory>${project.build.directory}/freemarker-unpacked</outputDirectory>
<includes>META-INF/LICENSE.txt,META-INF/NOTICE.txt</includes>
<includes>META-INF/LICENSE</includes>
</artifactItem>
</artifactItems>
</configuration>
@ -93,7 +100,7 @@
<doctitle>MapStruct ${project.version}</doctitle>
<windowtitle>MapStruct ${project.version}</windowtitle>
<bottom>
<![CDATA[Copyright &copy; ${project.inceptionYear}-{currentYear} <a href="http://mapstruct.org/">MapStruct Authors</a>; All rights reserved. Released under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache Software License 2.0</a>.]]>
<![CDATA[Copyright &copy; ${project.inceptionYear}-{currentYear} <a href="https://mapstruct.org/">MapStruct Authors</a>; All rights reserved. Released under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache Software License 2.0</a>.]]>
</bottom>
<groups>
@ -123,7 +130,7 @@
<!--
There is a bug in JDK 11 (https://bugs.openjdk.java.net/browse/JDK-8215291) which doesn't work correctly when searching and adds undefined.
It has been fixed since JDK 12, but not yet backported to JDK 11 (https://bugs.openjdk.java.net/browse/JDK-8244171).
One workardound is https://stackoverflow.com/a/57284322/1115491.
One workaround is https://stackoverflow.com/a/57284322/1115491.
-->
<bottom>
<![CDATA[
@ -155,7 +162,7 @@
<descriptor>${basedir}/src/main/assembly/dist.xml</descriptor>
</descriptors>
<finalName>mapstruct-${project.version}</finalName>
<tarLongFileMode>gnu</tarLongFileMode>
<tarLongFileMode>posix</tarLongFileMode>
</configuration>
<executions>
<execution>
@ -187,7 +194,6 @@
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>

View File

@ -42,11 +42,7 @@
<outputDirectory>/</outputDirectory>
</file>
<file>
<source>target/freemarker-unpacked/META-INF/NOTICE.txt</source>
<outputDirectory>/</outputDirectory>
</file>
<file>
<source>target/freemarker-unpacked/META-INF/LICENSE.txt</source>
<source>target/freemarker-unpacked/META-INF/LICENSE</source>
<outputDirectory>etc/freemarker</outputDirectory>
</file>
<file>

View File

@ -12,7 +12,7 @@
<parent>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-parent</artifactId>
<version>1.6.0-SNAPSHOT</version>
<version>1.7.0-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>

View File

@ -141,6 +141,8 @@ In the case that the `Fruit` is an abstract class or an interface, you would get
To allow mappings for abstract classes or interfaces you need to set the `subclassExhaustiveStrategy` to `RUNTIME_EXCEPTION`, you can do this at the `@MapperConfig`, `@Mapper` or `@BeanMapping` annotations. If you then pass a `GrapeDto` an `IllegalArgumentException` will be thrown because it is unknown how to map a `GrapeDto`.
Adding the missing (`@SubclassMapping`) for it will fix that.
<<selection-based-on-qualifiers>> can be used to further control which methods may be chosen to map a specific subclass. For that, you will need to use one of `SubclassMapping#qualifiedByName` or `SubclassMapping#qualifiedBy`.
[TIP]
====
If the mapping method for the subclasses does not exist it will be created and any other annotations on the fruit mapping method will be inherited by the newly generated mappings.
@ -279,7 +281,7 @@ First calling a mapping method on the source property is not protected by a null
The option `nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS` will always include a null check when source is non primitive, unless a source presence checker is defined on the source bean.
The strategy works in a hierarchical fashion. `@Mapping#nullValueCheckStrategy` will override `@BeanMapping#nullValueCheckStrategy`, `@BeanMapping#nullValueCheckStrategy` will override `@Mapper#nullValueCheckStrategy` and `@Mapper#nullValueCheckStrategy` will override `@MaperConfig#nullValueCheckStrategy`.
The strategy works in a hierarchical fashion. `@Mapping#nullValueCheckStrategy` will override `@BeanMapping#nullValueCheckStrategy`, `@BeanMapping#nullValueCheckStrategy` will override `@Mapper#nullValueCheckStrategy` and `@Mapper#nullValueCheckStrategy` will override `@MapperConfig#nullValueCheckStrategy`.
[[source-presence-check]]
=== Source presence checking
@ -292,7 +294,7 @@ The source presence checker name can be changed in the MapStruct service provide
[NOTE]
====
Some types of mappings (collections, maps), in which MapStruct is instructed to use a getter or adder as target accessor see `CollectionMappingStrategy`, MapStruct will always generate a source property
Some types of mappings (collections, maps), in which MapStruct is instructed to use a getter or adder as target accessor (see `CollectionMappingStrategy`), MapStruct will always generate a source property
null check, regardless the value of the `NullValueCheckStrategy` to avoid addition of `null` to the target collection or map.
====
@ -301,10 +303,12 @@ null check, regardless the value of the `NullValueCheckStrategy` to avoid additi
Conditional Mapping is a type of <<source-presence-check>>.
The difference is that it allows users to write custom condition methods that will be invoked to check if a property needs to be mapped or not.
Conditional mapping can also be used to check if a source parameter should be mapped or not.
A custom condition method is a method that is annotated with `org.mapstruct.Condition` and returns `boolean`.
A custom condition method for properties is a method that is annotated with `org.mapstruct.Condition` and returns `boolean`.
A custom condition method for source parameters is annotated with `org.mapstruct.SourceParameterCondition`, `org.mapstruct.Condition(appliesTo = org.mapstruct.ConditionStrategy#SOURCE_PARAMETERS)` or meta-annotated with `Condition(appliesTo = ConditionStrategy#SOURCE_PARAMETERS)`
e.g. if you only want to map a String property when it is not `null, and it is not empty then you can do something like:
e.g. if you only want to map a String property when it is not `null` and not empty then you can do something like:
.Mapper using custom condition check method
====
@ -404,6 +408,69 @@ public class CarMapperImpl implements CarMapper {
----
====
Additionally `@TargetPropertyName` or `@SourcePropertyName` of type `java.lang.String` can be used in custom condition check method:
.Mapper using custom condition check method with `@TargetPropertyName` and `@SourcePropertyName`
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
@Mapper
public interface CarMapper {
@Mapping(target = "owner", source = "ownerName")
CarDto carToCarDto(Car car, @MappingTarget CarDto carDto);
@Condition
default boolean isNotEmpty(
String value,
@TargetPropertyName String targetPropertyName,
@SourcePropertyName String sourcePropertyName
) {
if ( targetPropertyName.equals( "owner" )
&& sourcePropertyName.equals( "ownerName" ) ) {
return value != null
&& !value.isEmpty()
&& !value.equals( value.toLowerCase() );
}
return value != null && !value.isEmpty();
}
}
----
====
The generated mapper with `@TargetPropertyName` and `@SourcePropertyName` will look like:
.Custom condition check in generated implementation
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
// GENERATED CODE
public class CarMapperImpl implements CarMapper {
@Override
public CarDto carToCarDto(Car car, CarDto carDto) {
if ( car == null ) {
return carDto;
}
if ( isNotEmpty( car.getOwner(), "owner", "ownerName" ) ) {
carDto.setOwner( car.getOwner() );
} else {
carDto.setOwner( null );
}
// Mapping of other properties
return carDto;
}
}
----
====
[IMPORTANT]
====
If there is a custom `@Condition` method applicable for the property it will have a precedence over a presence check method in the bean itself.
@ -412,11 +479,62 @@ If there is a custom `@Condition` method applicable for the property it will hav
[NOTE]
====
Methods annotated with `@Condition` in addition to the value of the source property can also have the source parameter as an input.
`@TargetPropertyName` and `@SourcePropertyName` parameters can only be used in `@Condition` methods.
====
<<selection-based-on-qualifiers>> is also valid for `@Condition` methods.
In order to use a more specific condition method you will need to use one of `Mapping#conditionQualifiedByName` or `Mapping#conditionQualifiedBy`.
If we want to only map cars that have an id provided then we can do something like:
.Mapper using custom condition source parameter check method
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
@Mapper
public interface CarMapper {
CarDto carToCarDto(Car car);
@SourceParameterCondition
default boolean hasCar(Car car) {
return car != null && car.getId() != null;
}
}
----
====
The generated mapper will look like:
.Custom condition source parameter check generated implementation
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
// GENERATED CODE
public class CarMapperImpl implements CarMapper {
@Override
public CarDto carToCarDto(Car car) {
if ( !hasCar( car ) ) {
return null;
}
CarDto carDto = new CarDto();
carDto.setOwner( car.getOwner() );
// Mapping of other properties
return carDto;
}
}
----
====
[[exceptions]]
=== Exceptions

View File

@ -248,9 +248,8 @@ All before/after-mapping methods that *can* be applied to a mapping method *will
The order of the method invocation is determined primarily by their variant:
1. `@BeforeMapping` methods without an `@MappingTarget` parameter are called before any null-checks on source
parameters and constructing a new target bean.
2. `@BeforeMapping` methods with an `@MappingTarget` parameter are called after constructing a new target bean.
1. `@BeforeMapping` methods without parameters, a `@MappingTarget` parameter or a `@TargetType` parameter are called before any null-checks on source parameters and constructing a new target bean.
2. `@BeforeMapping` methods with a `@MappingTarget` parameter are called after constructing a new target bean.
3. `@AfterMapping` methods are called at the end of the mapping method before the last `return` statement.
Within those groups, the method invocations are ordered by their location of definition:
@ -262,4 +261,11 @@ Within those groups, the method invocations are ordered by their location of def
*Important:* the order of methods declared within one type can not be guaranteed, as it depends on the compiler and the processing environment implementation.
*Important:* when using a builder, the `@AfterMapping` annotated method must have the builder as `@MappingTarget` annotated parameter so that the method is able to modify the object going to be build. The `build` method is called when the `@AfterMapping` annotated method scope finishes. MapStruct will not call the `@AfterMapping` annotated method if the real target is used as `@MappingTarget` annotated parameter.
[NOTE]
====
Before/After-mapping methods can also be used with builders:
* `@BeforeMapping` methods with a `@MappingTarget` parameter of the real target will not be invoked because it is only available after the mapping was already performed.
* To be able to modify the object that is going to be built, the `@AfterMapping` annotated method must have the builder as `@MappingTarget` annotated parameter. The `build` method is called when the `@AfterMapping` annotated method scope finishes.
* The `@AfterMapping` annotated method can also have the real target as `@TargetType` or `@MappingTarget`. It will be invoked after the real target was built (first the methods annotated with `@TargetType`, then the methods annotated with `@MappingTarget`)
====

View File

@ -71,7 +71,7 @@ public class GolfPlayerDto {
public GolfPlayerDto withName(String name) {
this.name = name;
return this
return this;
}
}
----
@ -370,4 +370,55 @@ A nice example is to provide support for a custom transformation strategy.
----
include::{processor-ap-test}/value/nametransformation/CustomEnumTransformationStrategy.java[tag=documentation]
----
====
[[additional-supported-options-provider]]
=== Additional Supported Options Provider
SPI name: `org.mapstruct.ap.spi.AdditionalSupportedOptionsProvider`
MapStruct offers the ability to pass through declared compiler args (or "options") provided to the MappingProcessor
to the individual SPIs, by implementing `AdditionalSupportedOptionsProvider` via the Service Provider Interface (SPI).
.Custom Additional Supported Options Provider that declares `myorg.custom.defaultNullEnumConstant` as an option to pass through
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
include::{processor-ap-test}/additionalsupportedoptions/CustomAdditionalSupportedOptionsProvider.java[tag=documentation]
----
====
The value of this option is provided by including an `arg` to the `compilerArgs` tag when defining your custom SPI
implementation.
.Example maven configuration with additional options
====
[source, maven, linenums]
[subs="verbatim,attributes"]
----
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.myorg</groupId>
<artifactId>custom-spi-impl</artifactId>
<version>${project.version}</version>
</path>
</annotationProcessorPaths>
<compilerArgs>
<arg>-Amyorg.custom.defaultNullEnumConstant=MISSING</arg>
</compilerArgs>
</configuration>
----
====
Your custom SPI implementations can then access this configured value via `MapStructProcessingEnvironment#getOptions()`.
.Accessing your custom options
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
include::{processor-ap-test}/additionalsupportedoptions/UnknownEnumMappingStrategy.java[tag=documentation]
----
====

View File

@ -46,8 +46,10 @@ public @interface Default {
MapStruct works together with https://projectlombok.org/[Project Lombok] as of MapStruct 1.2.0.Beta1 and Lombok 1.16.14.
MapStruct takes advantage of generated getters, setters, and constructors and uses them to generate the mapper implementations.
Be reminded that the generated code by Lombok might not always be compatible with the expectations from the individual mappings.
In such a case, either Mapstruct mapping must be changed or Lombok must be configured accordingly using https://projectlombok.org/features/configuration[`lombok.config`] for mutual synergy.
[NOTE]
[WARNING]
====
Lombok 1.18.16 introduces a breaking change (https://projectlombok.org/changelog[changelog]).
The additional annotation processor `lombok-mapstruct-binding` (https://mvnrepository.com/artifact/org.projectlombok/lombok-mapstruct-binding[Maven]) must be added otherwise MapStruct stops working with Lombok.

View File

@ -130,7 +130,7 @@ You can find a complete example in the https://github.com/mapstruct/mapstruct-ex
The MapStruct code generator can be configured using _annotation processor options_.
When invoking javac directly, these options are passed to the compiler in the form _-Akey=value_. When using MapStruct via Maven, any processor options can be passed using an `options` element within the configuration of the Maven processor plug-in like this:
When invoking javac directly, these options are passed to the compiler in the form _-Akey=value_. When using MapStruct via Maven, any processor options can be passed using `compilerArgs` within the configuration of the Maven processor plug-in like this:
.Maven configuration
====
@ -215,10 +215,11 @@ suppressGeneratorVersionInfoComment`
Supported values are:
* `default`: the mapper uses no component model, instances are typically retrieved via `Mappers#getMapper(Class)`
* `cdi`: the generated mapper is an application-scoped CDI bean and can be retrieved via `@Inject`
* `cdi`: the generated mapper is an application-scoped (from javax.enterprise.context or jakarta.enterprise.context, depending on which one is available with javax.inject having priority) CDI bean and can be retrieved via `@Inject`
* `spring`: the generated mapper is a singleton-scoped Spring bean and can be retrieved via `@Autowired`
* `jsr330`: the generated mapper is annotated with {@code @Named} and can be retrieved via `@Inject` (from javax.inject or jakarta.inject, depending which one is available with javax.inject having priority), e.g. using Spring
* `jakarta`: the generated mapper is annotated with {@code @Named} and can be retrieved via `@Inject` (from jakarta.inject), e.g. using Spring
* `jakarta-cdi`: the generated mapper is an application-scoped (from jakarta.enterprise.context) CDI bean and can be retrieved via `@Inject`
If a component model is given for a specific mapper via `@Mapper#componentModel()`, the value from the annotation takes precedence.
|`default`
@ -260,12 +261,36 @@ Supported values are:
If a policy is given for a specific mapper via `@Mapper#unmappedSourcePolicy()`, the value from the annotation takes precedence.
If a policy is given for a specific bean mapping via `@BeanMapping#ignoreUnmappedSourceProperties()`, it takes precedence over both `@Mapper#unmappedSourcePolicy()` and the option.
|`WARN`
|`IGNORE`
|`mapstruct.
disableBuilders`
|If set to `true`, then MapStruct will not use builder patterns when doing the mapping. This is equivalent to doing `@Mapper( builder = @Builder( disableBuilder = true ) )` for all of your mappers.
|`false`
|`mapstruct.nullValueIterableMappingStrategy`
|The strategy to be applied when `null` is passed as a source value to an iterable mapping.
Supported values are:
* `RETURN_NULL`: if `null` is passed as a source value, then `null` will be returned
* `RETURN_DEFAULT`: if `null` is passed then a default value (empty collection) will be returned
If a strategy is given for a specific mapper via `@Mapper#nullValueIterableMappingStrategy()`, the value from the annotation takes precedence.
If a strategy is given for a specific iterable mapping via `@IterableMapping#nullValueMappingStrategy()`, it takes precedence over both `@Mapper#nullValueIterableMappingStrategy()` and the option.
|`RETURN_NULL`
|`mapstruct.nullValueMapMappingStrategy`
|The strategy to be applied when `null` is passed as a source value to a map mapping.
Supported values are:
* `RETURN_NULL`: if `null` is passed as a source value, then `null` will be returned
* `RETURN_DEFAULT`: if `null` is passed then a default value (empty map) will be returned
If a strategy is given for a specific mapper via `@Mapper#nullValueMapMappingStrategy()`, the value from the annotation takes precedence.
If a strategy is given for a specific map mapping via `@MapMapping#nullValueMappingStrategy()`, it takes precedence over both `@Mapper#nullValueMapMappingStrategy()` and the option.
|`RETURN_NULL`
|===
=== Using MapStruct with the Java Module System
@ -273,3 +298,28 @@ disableBuilders`
MapStruct can be used with Java 9 and higher versions.
To allow usage of the `@Generated` annotation `java.annotation.processing.Generated` (part of the `java.compiler` module) can be enabled.
=== IDE Integration
There are optional MapStruct plugins for IntelliJ and Eclipse that allow you to have additional completion support (and more) in the annotations.
==== IntelliJ
The https://plugins.jetbrains.com/plugin/10036-mapstruct-support[MapStruct IntelliJ] plugin offers assistance in projects that use MapStruct.
Some features include:
* Code completion in `target`, `source`, `expression`
* Go To Declaration for properties in `target` and `source`
* Find Usages of properties in `target` and `source`
* Refactoring support
* Errors and Quick Fixes
==== Eclipse
The https://marketplace.eclipse.org/content/mapstruct-eclipse-plugin[MapStruct Eclipse] Plugin offers assistance in projects that use MapStruct.
Some features include:
* Code completion in `target` and `source`
* Quick Fixes

View File

@ -39,7 +39,7 @@ The property name as defined in the http://www.oracle.com/technetwork/java/javas
====
[TIP]
====
By means of the `@BeanMapping(ignoreByDefault = true)` the default behavior will be *explicit mapping*, meaning that all mappings have to be specified by means of the `@Mapping` and no warnings will be issued on missing target properties.
By means of the `@BeanMapping(ignoreByDefault = true)` the default behavior will be *explicit mapping*, meaning that all mappings (including nested ones) have to be specified by means of the `@Mapping` and no warnings will be issued on missing target properties.
This allows to ignore all fields, except the ones that are explicitly defined through `@Mapping`.
====
[TIP]
@ -126,7 +126,7 @@ Collection-typed attributes with the same element type will be copied by creatin
MapStruct takes all public properties of the source and target types into account. This includes properties declared on super-types.
[[mapping-composition]]
=== Mapping Composition (experimental)
=== Mapping Composition
MapStruct supports the use of meta annotations. The `@Mapping` annotation supports now `@Target` with `ElementType#ANNOTATION_TYPE` in addition to `ElementType#METHOD`. This allows `@Mapping` to be used on other (user defined) annotations for re-use purposes. For example:
====
@ -164,7 +164,7 @@ public interface StorageMapper {
Still, they do have some properties in common. The `@ToEntity` assumes both target beans `ShelveEntity` and `BoxEntity` have properties: `"id"`, `"creationDate"` and `"name"`. It furthermore assumes that the source beans `ShelveDto` and `BoxDto` always have a property `"groupName"`. This concept is also known as "duck-typing". In other words, if it quacks like duck, walks like a duck its probably a duck.
This feature is still experimental. Error messages are not mature yet: the method on which the problem occurs is displayed, as well as the concerned values in the `@Mapping` annotation. However, the composition aspect is not visible. The messages are "as if" the `@Mapping` would be present on the concerned method directly.
Error messages are not mature yet: the method on which the problem occurs is displayed, as well as the concerned values in the `@Mapping` annotation. However, the composition aspect is not visible. The messages are "as if" the `@Mapping` would be present on the concerned method directly.
Therefore, the user should use this feature with care, especially when uncertain when a property is always present.
A more typesafe (but also more verbose) way would be to define base classes / interfaces on the target bean and the source bean and use `@InheritConfiguration` to achieve the same result (see <<mapping-configuration-inheritance>>).
@ -302,7 +302,7 @@ If you don't want explicitly name all properties from nested source bean, you ca
The generated code will map every property from `CustomerDto.record` to `Customer` directly, without need to manually name any of them.
The same goes for `Customer.account`.
When there are conflicts, these can be resolved by explicitely defining the mapping. For instance in the example above. `name` occurs in `CustomerDto.record` and in `CustomerDto.account`. The mapping `@Mapping( target = "name", source = "record.name" )` resolves this conflict.
When there are conflicts, these can be resolved by explicitly defining the mapping. For instance in the example above. `name` occurs in `CustomerDto.record` and in `CustomerDto.account`. The mapping `@Mapping( target = "name", source = "record.name" )` resolves this conflict.
This "target this" notation can be very useful when mapping hierarchical objects to flat objects and vice versa (`@InheritInverseConfiguration`).
@ -421,8 +421,11 @@ If a Builder exists for a certain type, then that builder will be used for the m
The default implementation of the `BuilderProvider` assumes the following:
* The type has a parameterless public static builder creation method that returns a builder.
So for example `Person` has a public static method that returns `PersonBuilder`.
* The type has either
** A parameterless public static builder creation method that returns a builder.
e.g. `Person` has a public static method that returns `PersonBuilder`.
** A public static inner class with the name having the suffix "Builder", and a public no-args constructor
e.g. `Person` has an inner class `PersonBuilder` with a public no-args constructor.
* The builder type has a parameterless public method (build method) that returns the type being built.
In our example `PersonBuilder` has a method returning `Person`.
* In case there are multiple build methods, MapStruct will look for a method called `build`, if such method exists
@ -448,7 +451,7 @@ E.g. If an object factory exists for our `PersonBuilder` then this factory would
[NOTE]
======
Detected builders influence `@BeforeMapping` and `@AfterMapping` behavior. See chapter `Mapping customization with before-mapping and after-mapping methods` for more information.
Detected builders influence `@BeforeMapping` and `@AfterMapping` behavior. See <<customizing-mappings-with-before-and-after>> for more information.
======
.Person with Builder example
@ -721,3 +724,143 @@ i.e. You can map from `Map<String, Integer>` where for each property a conversio
When a raw map or a map that does not have a String as a key is used, then a warning will be generated.
The warning is not generated if the map itself is mapped into some other target property directly as is.
====
[[adding-annotations]]
=== Adding annotations
Other frameworks sometimes requires you to add annotations to certain classes so that they can easily detect the mappers.
Using the `@AnnotateWith` annotation you can generate an annotation at the specified location.
For example Apache Camel has a `@Converter` annotation which you can apply to generated mappers using the `@AnnotateWith` annotation.
.AnnotateWith source example
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
@Mapper
@AnnotateWith(
value = Converter.class,
elements = @AnnotateWith.Element( name = "generateBulkLoader", booleans = true )
)
public interface MyConverter {
@AnnotateWith( Converter.class )
DomainObject map( DtoObject dto );
}
----
====
.AnnotateWith generated mapper
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
@Converter( generateBulkLoader = true )
public class MyConverterImpl implements MyConverter {
@Converter
public DomainObject map( DtoObject dto ) {
// default mapping behaviour
}
}
----
====
[[javadoc]]
=== Adding Javadoc comments
MapStruct provides support for defining Javadoc comments in the generated mapper implementation using the
`org.mapstruct.Javadoc` annotation.
This functionality could be relevant especially in situations where certain Javadoc standards need to be met or
to deal with Javadoc validation constraints.
The `@Javadoc` annotation defines attributes for the different Javadoc elements.
Consider the following example:
.Javadoc annotation example
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
@Mapper
@Javadoc(
value = "This is the description",
authors = { "author1", "author2" },
deprecated = "Use {@link OtherMapper} instead",
since = "0.1"
)
public interface MyAnnotatedWithJavadocMapper {
//...
}
----
====
.Javadoc annotated generated mapper
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
/**
* This is the description
*
* @author author1
* @author author2
*
* @deprecated Use {@link OtherMapper} instead
* @since 0.1
*/
public class MyAnnotatedWithJavadocMapperImpl implements MyAnnotatedWithJavadocMapper {
//...
}
----
====
The entire Javadoc comment block can be provided directly as well.
.Javadoc annotation example with the entire Javadoc comment block provided directly
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
@Mapper
@Javadoc(
"This is the description\n"
+ "\n"
+ "@author author1\n"
+ "@author author2\n"
+ "\n"
+ "@deprecated Use {@link OtherMapper} instead\n"
+ "@since 0.1\n"
)
public interface MyAnnotatedWithJavadocMapper {
//...
}
----
====
Or using Text blocks:
.Javadoc annotation example with the entire Javadoc comment block provided directly using Text blocks
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
@Mapper
@Javadoc(
"""
This is the description
@author author1
@author author2
@deprecated Use {@link OtherMapper} instead
@since 0.1
"""
)
public interface MyAnnotatedWithJavadocMapper {
//...
}
----
====

View File

@ -102,7 +102,7 @@ A mapper which uses other mapper classes (see <<invoking-other-mappers>>) will o
[[injection-strategy]]
=== Injection strategy
When using <<using-dependency-injection,dependency injection>>, you can choose between field and constructor injection.
When using <<using-dependency-injection,dependency injection>>, you can choose between constructor, field, or setter injection.
This can be done by either providing the injection strategy via `@Mapper` or `@MapperConfig` annotation.
.Using constructor injection
@ -120,9 +120,13 @@ public interface CarMapper {
The generated mapper will inject classes defined in the **uses** attribute if MapStruct has detected that it needs to use an instance of it for a mapping.
When `InjectionStrategy#CONSTRUCTOR` is used, the constructor will have the appropriate annotation and the fields won't.
When `InjectionStrategy#FIELD` is used, the annotation is on the field itself.
When `InjectionStrategy#SETTER` is used the annotation is on a generated setter method.
For now, the default injection strategy is field injection, but it can be configured with <<configuration-options>>.
It is recommended to use constructor injection to simplify testing.
When you define mappers in Spring with circular dependencies compilation may fail.
In that case utilize the `InjectionStrategy#SETTER` strategy.
[TIP]
====
For abstract classes or decorators setter injection should be used.

View File

@ -43,6 +43,9 @@ public interface CarMapper {
====
* Between `enum` types and `String`.
* Between `enum` types and `Integer`, according to `enum.ordinal()`.
** When converting from an `Integer`, the value needs to be less than the number of values of the enum, otherwise an `ArrayOutOfBoundsException` is thrown.
* Between big number types (`java.math.BigInteger`, `java.math.BigDecimal`) and Java primitive types (including their wrappers) as well as String. A format string as understood by `java.text.DecimalFormat` can be specified.
.Conversion from BigDecimal to String
@ -104,6 +107,8 @@ public interface CarMapper {
* Between `java.time.Instant` from Java 8 Date-Time package and `java.util.Date`.
* Between `java.time.LocalDateTime` from Java 8 Date-Time package and `java.time.LocalDate` from the same package.
* Between `java.time.ZonedDateTime` from Java 8 Date-Time package and `java.util.Calendar`.
* Between `java.sql.Date` and `java.util.Date`
@ -125,6 +130,9 @@ public interface CarMapper {
* Between `java.net.URL` and `String`.
** When converting from a `String`, the value needs to be a valid https://en.wikipedia.org/wiki/URL[URL] otherwise a `MalformedURLException` is thrown.
* Between `java.util.Locale` and `String`.
** When converting from a `Locale`, the resulting `String` will be a well-formed IETF BCP 47 language tag representing the locale. When converting from a `String`, the locale that best represents the language tag will be returned. See https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html#forLanguageTag-java.lang.String-[Locale.forLanguageTag()] and https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html#toLanguageTag--[Locale.toLanguageTag()] for more information.
[[mapping-object-references]]
=== Mapping object references
@ -272,6 +280,13 @@ This puts the configuration of the nested mapping into one place (method) where
instead of re-configuring the same things on all of those upper methods.
====
[TIP]
====
When ignoring multiple properties instead of defining multiple `@Mapping` annotations, you can use the `@Ignored` annotation to group them together.
e.g. for the `FishTankMapperWithDocument` example above, you could write:
`@Ignored(targets = { "plant", "ornament", "material" })`
====
[NOTE]
====
In some cases the `ReportingPolicy` that is going to be used for the generated nested method would be `IGNORE`.
@ -393,6 +408,39 @@ When having a custom mapper hooked into the generated mapper with `@Mapper#uses(
For instance, the `CarDto` could have a property `owner` of type `Reference` that contains the primary key of a `Person` entity. You could now create a generic custom mapper that resolves any `Reference` objects to their corresponding managed JPA entity instances.
e.g.
.Example classes for the passing target type example
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
public class Car {
private Person owner;
// ...
}
public class Person extends BaseEntity {
// ...
}
public class Reference {
private String pk;
// ...
}
public class CarDto {
private Reference owner;
// ...
}
----
====
.Mapping method expecting mapping target type as parameter
====
[source, java, linenums]

View File

@ -192,7 +192,7 @@ The option `DEFAULT` should not be used explicitly. It is used to distinguish be
[TIP]
====
When working with an `adder` method and JPA entities, Mapstruct assumes that the target collections are initialized with a collection implementation (e.g. an `ArrayList`). You can use factories to create a new target entity with intialized collections instead of Mapstruct creating the target entity by its constructor.
When working with an `adder` method and JPA entities, Mapstruct assumes that the target collections are initialized with a collection implementation (e.g. an `ArrayList`). You can use factories to create a new target entity with initialized collections instead of Mapstruct creating the target entity by its constructor.
====
[[implementation-types-for-collection-mappings]]
@ -212,16 +212,20 @@ When an iterable or map mapping method declares an interface type as return type
|`Set`|`LinkedHashSet`
|`SequencedSet`|`LinkedHashSet`
|`SortedSet`|`TreeSet`
|`NavigableSet`|`TreeSet`
|`Map`|`LinkedHashMap`
|`SequencedMap`|`LinkedHashMap`
|`SortedMap`|`TreeMap`
|`NavigableMap`|`TreeMap`
|`ConcurrentMap`|`ConcurrentHashMap`
|`ConcurrentNavigableMap`|`ConcurrentSkipListMap`
|===
|===

View File

@ -65,7 +65,7 @@ public class OrderMapperImpl implements OrderMapper {
----
====
By default an error will be raised by MapStruct in case a constant of the source enum type does not have a corresponding constant with the same name in the target type and also is not mapped to another constant via `@ValueMapping`. This ensures that all constants are mapped in a safe and predictable manner. The generated
mapping method will throw an IllegalStateException if for some reason an unrecognized source value occurs.
mapping method will throw an `IllegalStateException` if for some reason an unrecognized source value occurs.
MapStruct also has a mechanism for mapping any remaining (unspecified) mappings to a default. This can be used only once in a set of value mappings and only applies to the source. It comes in two flavors: `<ANY_REMAINING>` and `<ANY_UNMAPPED>`. They cannot be used at the same time.
@ -75,14 +75,18 @@ MapStruct will *not* attempt such name based mapping for `<ANY_UNMAPPED>` and di
MapStruct is able to handle `null` sources and `null` targets by means of the `<NULL>` keyword.
In addition, the constant value `<THROW_EXCEPTION>` can be used for throwing an exception for particular value mappings. This value is only applicable to `ValueMapping#target()` and not `ValueMapping#source()` since MapStruct can't map from exceptions.
[TIP]
====
Constants for `<ANY_REMAINING>`, `<ANY_UNMAPPED>` and `<NULL>` are available in the `MappingConstants` class.
Constants for `<ANY_REMAINING>`, `<ANY_UNMAPPED>`, `<THROW_EXCEPTION>` and `<NULL>` are available in the `MappingConstants` class.
====
Finally `@InheritInverseConfiguration` and `@InheritConfiguration` can be used in combination with `@ValueMappings`. `<ANY_REMAINING>` and `<ANY_UNMAPPED>` will be ignored in that case.
.Enum mapping method, <NULL> and <ANY_REMAINING>
The following code snippets exemplify the use of the aforementioned constants.
.Enum mapping method, `<NULL>` and `<ANY_REMAINING>`
====
[source, java, linenums]
[subs="verbatim,attributes"]
@ -102,7 +106,7 @@ public interface SpecialOrderMapper {
----
====
.Enum mapping method result, <NULL> and <ANY_REMAINING>
.Enum mapping method result, `<NULL>` and `<ANY_REMAINING>`
====
[source, java, linenums]
[subs="verbatim,attributes"]
@ -137,9 +141,52 @@ public class SpecialOrderMapperImpl implements SpecialOrderMapper {
*Note:* MapStruct would have refrained from mapping the `RETAIL` and `B2B` when `<ANY_UNMAPPED>` was used instead of `<ANY_REMAINING>`.
[WARNING]
.Enum mapping method with `<THROW_EXCEPTION>`
====
The mapping of enum to enum via the `@Mapping` annotation is *DEPRECATED*. It will be removed from future versions of MapStruct. Please adapt existing enum mapping methods to make use of `@ValueMapping` instead.
[source, java, linenums]
[subs="verbatim,attributes"]
----
@Mapper
public interface SpecialOrderMapper {
SpecialOrderMapper INSTANCE = Mappers.getMapper( SpecialOrderMapper.class );
@ValueMappings({
@ValueMapping( source = "STANDARD", target = "DEFAULT" ),
@ValueMapping( source = "C2C", target = MappingConstants.THROW_EXCEPTION )
})
ExternalOrderType orderTypeToExternalOrderType(OrderType orderType);
}
----
====
.Enum mapping method with `<THROW_EXCEPTION>` result
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
// GENERATED CODE
public class SpecialOrderMapperImpl implements SpecialOrderMapper {
@Override
public ExternalOrderType orderTypeToExternalOrderType(OrderType orderType) {
if ( orderType == null ) {
return null;
}
ExternalOrderType externalOrderType;
switch ( orderType ) {
case STANDARD: externalOrderType = ExternalOrderType.DEFAULT;
break;
case C2C: throw new IllegalArgumentException( "Unexpected enum constant: " + orderType );
default: throw new IllegalArgumentException( "Unexpected enum constant: " + orderType );
}
return externalOrderType;
}
}
----
====
=== Mapping enum-to-String or String-to-enum
@ -152,6 +199,7 @@ MapStruct supports enum to a String mapping along the same lines as is described
2. Similarity: `<ANY_UNMAPPED`> stops after handling defined mapping and proceeds to the switch/default clause value.
3. Difference: `<ANY_REMAINING>` will result in an error. It acts on the premise that there is name similarity between enum constants in source and target which does not make sense for a String type.
4. Difference: Given 1. and 3. there will never be unmapped values.
5. Similarity: `<THROW_EXCEPTION>` can be used for throwing an exception for particular enum values.
*`String` to enum*
@ -159,6 +207,7 @@ MapStruct supports enum to a String mapping along the same lines as is described
2. Similarity: `<ANY_UNMAPPED`> stops after handling defined mapping and proceeds to the switch/default clause value.
3. Similarity: `<ANY_REMAINING>` will create a mapping for each target enum constant and proceed to the switch/default clause value.
4. Difference: A switch/default value needs to be provided to have a determined outcome (enum has a limited set of values, `String` has unlimited options). Failing to specify `<ANY_REMAINING>` or `<ANY_UNMAPPED`> will result in a warning.
5. Similarity: `<THROW_EXCEPTION>` can be used for throwing an exception for any arbitrary `String` value.
=== Custom name transformation
@ -266,3 +315,42 @@ MapStruct provides the following out of the box enum name transformation strateg
It is also possible to register custom strategies.
For more information on how to do that have a look at <<custom-enum-transformation-strategy>>
[[value-mapping-composition]]
=== ValueMapping Composition
The `@ValueMapping` annotation supports now `@Target` with `ElementType#ANNOTATION_TYPE` in addition to `ElementType#METHOD`.
This allows `@ValueMapping` to be used on other (user defined) annotations for re-use purposes.
For example:
.Custom value mapping annotations
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
@Retention( RetentionPolicy.CLASS )
@ValueMapping(source = "EXTRA", target = "SPECIAL")
@ValueMapping(source = MappingConstants.ANY_REMAINING, target = "DEFAULT")
public @interface CustomValueAnnotation {
}
----
====
It can be used to describe some common value mapping relationships to avoid duplicate declarations, as in the following example:
.Using custom combination annotations
====
[source, java, linenums]
[subs="verbatim,attributes"]
----
@Mapper
public interface ValueMappingCompositionMapper {
@CustomValueAnnotation
ExternalOrderType orderTypeToExternalOrderType(OrderType orderType);
@CustomValueAnnotation
@ValueMapping(source = "STANDARD", target = "SPECIAL")
ExternalOrderType duplicateAnnotation(OrderType orderType);
}
----
====

View File

@ -12,7 +12,7 @@
<parent>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-parent</artifactId>
<version>1.6.0-SNAPSHOT</version>
<version>1.7.0-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>
@ -133,8 +133,8 @@
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
</dependencies>
</profile>

View File

@ -26,16 +26,36 @@ public final class FullFeatureCompilationExclusionCliEnhancer implements Process
// SPI not working correctly here.. (not picked up)
additionalExcludes.add( "org/mapstruct/ap/test/bugs/_1596/*.java" );
additionalExcludes.add( "org/mapstruct/ap/test/bugs/_1801/*.java" );
additionalExcludes.add( "org/mapstruct/ap/test/bugs/_3089/*.java" );
switch ( currentJreVersion ) {
case JAVA_8:
additionalExcludes.add( "org/mapstruct/ap/test/**/spring/**/*.java" );
additionalExcludes.add( "org/mapstruct/ap/test/injectionstrategy/cdi/**/*.java" );
additionalExcludes.add( "org/mapstruct/ap/test/injectionstrategy/jakarta_cdi/**/*.java" );
additionalExcludes.add( "org/mapstruct/ap/test/annotatewith/deprecated/jdk11/*.java" );
additionalExcludes.add( "org/mapstruct/ap/test/**/jdk21/*.java" );
if ( processorType == ProcessorTest.ProcessorType.ECLIPSE_JDT ) {
additionalExcludes.add(
"org/mapstruct/ap/test/selection/methodgenerics/wildcards/LifecycleIntersectionMapper.java" );
}
break;
case JAVA_9:
// TODO find out why this fails:
additionalExcludes.add( "org/mapstruct/ap/test/collection/wildcard/BeanMapper.java" );
additionalExcludes.add( "org/mapstruct/ap/test/**/jdk21/*.java" );
break;
case JAVA_11:
additionalExcludes.add( "org/mapstruct/ap/test/**/spring/**/*.java" );
additionalExcludes.add( "org/mapstruct/ap/test/**/jdk21/*.java" );
break;
case JAVA_17:
additionalExcludes.add( "org/mapstruct/ap/test/**/jdk21/*.java" );
break;
default:
}
Collection<String> result = new ArrayList<String>( additionalExcludes.size() );
Collection<String> result = new ArrayList<>(additionalExcludes.size());
for ( int i = 0; i < additionalExcludes.size(); i++ ) {
result.add( "-DadditionalExclude" + i + "=" + additionalExcludes.get( i ) );
}

View File

@ -62,7 +62,7 @@ public class GradleIncrementalCompilationTest {
}
private GradleRunner getRunner(String... additionalArguments) {
List<String> fullArguments = new ArrayList<String>( compileArgs );
List<String> fullArguments = new ArrayList<>(compileArgs);
fullArguments.addAll( Arrays.asList( additionalArguments ) );
return runner.withArguments( fullArguments );
}

View File

@ -5,6 +5,7 @@
*/
package org.mapstruct.itest.tests;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.junit.jupiter.api.parallel.Execution;
@ -75,13 +76,20 @@ public class MavenIntegrationTest {
void jaxbTest() {
}
@ProcessorTest(baseDir = "jakartaJaxbTest")
void jakartaJaxbTest() {
}
@ProcessorTest(baseDir = "jsr330Test")
@EnabledForJreRange(min = JRE.JAVA_17)
@DisabledOnJre(JRE.OTHER)
void jsr330Test() {
}
@ProcessorTest(baseDir = "lombokBuilderTest", processorTypes = {
ProcessorTest.ProcessorType.JAVAC
})
@DisabledOnJre(JRE.OTHER)
void lombokBuilderTest() {
}
@ -90,6 +98,7 @@ public class MavenIntegrationTest {
ProcessorTest.ProcessorType.JAVAC_WITH_PATHS
})
@EnabledForJreRange(min = JRE.JAVA_11)
@DisabledOnJre(JRE.OTHER)
void lombokModuleTest() {
}
@ -108,6 +117,11 @@ public class MavenIntegrationTest {
void protobufBuilderTest() {
}
@ProcessorTest(baseDir = "sealedSubclassTest")
@EnabledForJreRange(min = JRE.JAVA_17)
void sealedSubclassTest() {
}
@ProcessorTest(baseDir = "recordsTest", processorTypes = {
ProcessorTest.ProcessorType.JAVAC
})
@ -122,6 +136,13 @@ public class MavenIntegrationTest {
void recordsCrossModuleTest() {
}
@ProcessorTest(baseDir = "recordsCrossModuleInterfaceTest", processorTypes = {
ProcessorTest.ProcessorType.JAVAC
})
@EnabledForJreRange(min = JRE.JAVA_17)
void recordsCrossModuleInterfaceTest() {
}
@ProcessorTest(baseDir = "expressionTextBlocksTest", processorTypes = {
ProcessorTest.ProcessorType.JAVAC
})
@ -134,6 +155,7 @@ public class MavenIntegrationTest {
}, forkJvm = true)
// We have to fork the jvm because there is an NPE in com.intellij.openapi.util.SystemInfo.getRtVersion
// and the kotlin-maven-plugin uses that. See also https://youtrack.jetbrains.com/issue/IDEA-238907
@DisabledOnJre(JRE.OTHER)
void kotlinDataTest() {
}
@ -147,6 +169,8 @@ public class MavenIntegrationTest {
}
@ProcessorTest(baseDir = "springTest")
@EnabledForJreRange(min = JRE.JAVA_17)
@DisabledOnJre(JRE.OTHER)
void springTest() {
}

View File

@ -134,14 +134,20 @@ public class ProcessorInvocationInterceptor implements InvocationInterceptor {
}
private void configureProcessor(Verifier verifier) {
String compilerId = processorTestContext.getProcessor().getCompilerId();
ProcessorTest.ProcessorType processor = processorTestContext.getProcessor();
String compilerId = processor.getCompilerId();
if ( compilerId != null ) {
String profile = processorTestContext.getProcessor().getProfile();
String profile = processor.getProfile();
if ( profile == null ) {
profile = "generate-via-compiler-plugin";
}
verifier.addCliOption( "-P" + profile );
verifier.addCliOption( "-Dcompiler-id=" + compilerId );
if ( processor == ProcessorTest.ProcessorType.JAVAC ) {
if ( CURRENT_VERSION.ordinal() >= JRE.JAVA_21.ordinal() ) {
verifier.addCliOption( "-Dmaven.compiler.proc=full" );
}
}
}
else {
verifier.addCliOption( "-Pgenerate-via-processor-plugin" );

View File

@ -25,6 +25,13 @@
<additionalExclude2>x</additionalExclude2>
<additionalExclude3>x</additionalExclude3>
<additionalExclude4>x</additionalExclude4>
<additionalExclude5>x</additionalExclude5>
<additionalExclude6>x</additionalExclude6>
<additionalExclude7>x</additionalExclude7>
<additionalExclude8>x</additionalExclude8>
<additionalExclude9>x</additionalExclude9>
<additionalExclude10>x</additionalExclude10>
<additionalExclude11>x</additionalExclude11>
</properties>
<build>
@ -45,6 +52,15 @@
<exclude>${additionalExclude2}</exclude>
<exclude>${additionalExclude3}</exclude>
<exclude>${additionalExclude4}</exclude>
<exclude>${additionalExclude5}</exclude>
<exclude>${additionalExclude6}</exclude>
<exclude>${additionalExclude7}</exclude>
<exclude>${additionalExclude8}</exclude>
<exclude>${additionalExclude9}</exclude>
<exclude>${additionalExclude10}</exclude>
<exclude>${additionalExclude11}</exclude>
<exclude>${additionalExclude12}</exclude>
<exclude>${additionalExclude13}</exclude>
</excludes>
</configuration>
</plugin>
@ -64,6 +80,10 @@
<groupId>jakarta.inject</groupId>
<artifactId>jakarta.inject-api</artifactId>
</dependency>
<dependency>
<groupId>jakarta.enterprise</groupId>
<artifactId>jakarta.enterprise.cdi-api</artifactId>
</dependency>
<!-- Spring -->
<dependency>
@ -79,6 +99,13 @@
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
</dependencies>
<profiles>
@ -89,14 +116,16 @@
</activation>
<dependencies>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.2</version>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.2</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
</dependencies>
</profile>

View File

@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright MapStruct Authors.
Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-it-parent</artifactId>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>jakartaJaxbTest</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>xjc</id>
<phase>initialize</phase>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<xjbSources>
<xjbSource>${project.build.resources[0].directory}/binding</xjbSource>
</xjbSources>
<sources>
<source>${project.build.resources[0].directory}/schema</source>
</sources>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,42 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.jakarta.jaxb;
import java.util.List;
/**
* @author Sjaak Derksen
*/
public class OrderDetailsDto {
private String name;
private List<String> description;
private OrderStatusDto status;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getDescription() {
return description;
}
public void setDescription(List<String> description) {
this.description = description;
}
public OrderStatusDto getStatus() {
return status;
}
public void setStatus(OrderStatusDto status) {
this.status = status;
}
}

View File

@ -0,0 +1,52 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.jakarta.jaxb;
import java.util.Date;
/**
* @author Sjaak Derksen
*/
public class OrderDto {
private Long orderNumber;
private Date orderDate;
private OrderDetailsDto orderDetails;
private ShippingAddressDto shippingAddress;
public Long getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(Long orderNumber) {
this.orderNumber = orderNumber;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public OrderDetailsDto getOrderDetails() {
return orderDetails;
}
public void setOrderDetails(OrderDetailsDto orderDetails) {
this.orderDetails = orderDetails;
}
public ShippingAddressDto getShippingAddress() {
return shippingAddress;
}
public void setShippingAddress(ShippingAddressDto shippingAddress) {
this.shippingAddress = shippingAddress;
}
}

View File

@ -0,0 +1,35 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.jakarta.jaxb;
/**
* @author Sjaak Derksen
*/
public enum OrderStatusDto {
ORDERED( "small" ),
PROCESSED( "medium" ),
DELIVERED( "large" );
private final String value;
OrderStatusDto(String v) {
value = v;
}
public String value() {
return value;
}
public static OrderStatusDto fromValue(String v) {
for ( OrderStatusDto c : OrderStatusDto.values() ) {
if ( c.value.equals( v ) ) {
return c;
}
}
throw new IllegalArgumentException( v );
}
}

View File

@ -0,0 +1,50 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.jakarta.jaxb;
/**
* @author Sjaak Derksen
*/
public class ShippingAddressDto {
private String street;
private String houseNumber;
private String city;
private String country;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getHouseNumber() {
return houseNumber;
}
public void setHouseNumber(String houseNumber) {
this.houseNumber = houseNumber;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}

View File

@ -0,0 +1,50 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.jakarta.jaxb;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import org.mapstruct.itest.jakarta.jaxb.xsd.test1.OrderDetailsType;
import org.mapstruct.itest.jakarta.jaxb.xsd.test1.OrderType;
import org.mapstruct.itest.jakarta.jaxb.xsd.test2.OrderStatusType;
import org.mapstruct.itest.jakarta.jaxb.xsd.test2.ShippingAddressType;
import org.mapstruct.itest.jakarta.jaxb.xsd.underscores.SubType;
/**
* @author Sjaak Derksen
*/
@Mapper(uses = {
org.mapstruct.itest.jakarta.jaxb.xsd.test1.ObjectFactory.class,
org.mapstruct.itest.jakarta.jaxb.xsd.test2.ObjectFactory.class,
org.mapstruct.itest.jakarta.jaxb.xsd.underscores.ObjectFactory.class
})
public interface SourceTargetMapper {
SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class );
// source 2 target methods
OrderDto sourceToTarget(OrderType source);
OrderDetailsDto detailsToDto(OrderDetailsType source);
OrderStatusDto statusToDto(OrderStatusType source);
ShippingAddressDto shippingAddressToDto(ShippingAddressType source);
SubTypeDto subTypeToDto(SubType source);
// target 2 source methods
OrderType targetToSource(OrderDto target);
OrderDetailsType dtoToDetails(OrderDetailsDto target);
OrderStatusType dtoToStatus(OrderStatusDto target);
ShippingAddressType dtoToShippingAddress(ShippingAddressDto source);
SubType dtoToSubType(SubTypeDto source);
}

View File

@ -0,0 +1,27 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.jakarta.jaxb;
public class SubTypeDto extends SuperTypeDto {
private String declaredCamelCase;
private String declaredUnderscore;
public String getDeclaredCamelCase() {
return declaredCamelCase;
}
public void setDeclaredCamelCase(String declaredCamelCase) {
this.declaredCamelCase = declaredCamelCase;
}
public String getDeclaredUnderscore() {
return declaredUnderscore;
}
public void setDeclaredUnderscore(String declaredUnderscore) {
this.declaredUnderscore = declaredUnderscore;
}
}

View File

@ -0,0 +1,27 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.jakarta.jaxb;
public class SuperTypeDto {
private String inheritedCamelCase;
private String inheritedUnderscore;
public String getInheritedCamelCase() {
return inheritedCamelCase;
}
public void setInheritedCamelCase(String inheritedCamelCase) {
this.inheritedCamelCase = inheritedCamelCase;
}
public String getInheritedUnderscore() {
return inheritedUnderscore;
}
public void setInheritedUnderscore(String inheritedUnderscore) {
this.inheritedUnderscore = inheritedUnderscore;
}
}

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright MapStruct Authors.
Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
-->
<jaxb:bindings xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
jaxb:extensionBindingPrefixes="xjc"
version="3.0" >
<jaxb:globalBindings
fixedAttributeAsConstantProperty="true"
typesafeEnumBase="xs:string"
typesafeEnumMemberName="generateName"
generateIsSetMethod="true"
generateElementProperty="true" >
<xjc:noValidator/>
<xjc:noValidatingUnmarshaller/>
</jaxb:globalBindings>
</jaxb:bindings>

View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright MapStruct Authors.
Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
-->
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:test1="http://www.mapstruct.org/itest/jakarta/jaxb/xsd/test1"
xmlns:test2="http://www.mapstruct.org/itest/jakarta/jaxb/xsd/test2"
targetNamespace="http://www.mapstruct.org/itest/jakarta/jaxb/xsd/test1"
elementFormDefault="qualified" version="1.0.0">
<import namespace="http://www.mapstruct.org/itest/jakarta/jaxb/xsd/test2" schemaLocation="test2.xsd"/>
<element name="Order" type="test1:OrderType" />
<complexType name="OrderType">
<sequence>
<element name="orderNumber" type="long"/>
<element name="orderDate" type="dateTime"/>
<element name="orderDetails" type="test1:OrderDetailsType"/>
<element name="shippingAddress" type="test2:ShippingAddressType"/>
</sequence>
</complexType>
<element name="OrderDetails" type="test1:OrderDetailsType" />
<complexType name="OrderDetailsType">
<sequence>
<element name="name" type="string"/>
<element name="description" minOccurs="1" maxOccurs="5" type="string"/>
<element name="status" type="test2:OrderStatusType"/>
</sequence>
</complexType>
</schema>

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright MapStruct Authors.
Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
-->
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:test2="http://www.mapstruct.org/itest/jakarta/jaxb/xsd/test2"
targetNamespace="http://www.mapstruct.org/itest/jakarta/jaxb/xsd/test2"
elementFormDefault="qualified" version="1.0.0">
<element name="OrderStatus" type="test2:OrderStatusType" />
<simpleType name="OrderStatusType">
<restriction base="string">
<enumeration value="ordered" />
<enumeration value="processed" />
<enumeration value="delivered" />
</restriction>
</simpleType>
<element name="ShippingAddress" type="test2:ShippingAddressType" />
<complexType name="ShippingAddressType">
<sequence>
<element name="street" type="string"/>
<element name="houseNumber" type="string"/>
<element name="city" type="string"/>
<element name="country" type="string"/>
</sequence>
</complexType>
</schema>

View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright MapStruct Authors.
Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
-->
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:underscores="http://www.mapstruct.org/itest/jakarta/jaxb/xsd/underscores"
targetNamespace="http://www.mapstruct.org/itest/jakarta/jaxb/xsd/underscores"
elementFormDefault="qualified" version="1.0.0">
<element name="Super" type="underscores:SuperType" />
<complexType name="SuperType">
<sequence>
<element name="inheritedCamelCase" type="string"/>
<element name="inherited_underscore" type="string"/>
</sequence>
</complexType>
<element name="Sub" type="underscores:SubType" />
<complexType name="SubType">
<complexContent>
<extension base="underscores:SuperType">
<sequence>
<element name="declaredCamelCase" type="string"/>
<element name="declared_underscore" type="string"/>
</sequence>
</extension>
</complexContent>
</complexType>
</schema>

View File

@ -0,0 +1,118 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.jakarta.jaxb;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;
import org.junit.Test;
import org.mapstruct.itest.jakarta.jaxb.xsd.test1.ObjectFactory;
import org.mapstruct.itest.jakarta.jaxb.xsd.test1.OrderType;
import org.mapstruct.itest.jakarta.jaxb.xsd.underscores.SubType;
/**
* Test for generation of Jakarta JAXB based mapper implementations.
*
* @author Iaroslav Bogdanchikov
*/
public class JakartaJaxbBasedMapperTest {
@Test
public void shouldMapJakartaJaxb() throws ParseException, JAXBException {
SourceTargetMapper mapper = SourceTargetMapper.INSTANCE;
OrderDto source1 = new OrderDto();
source1.setOrderDetails( new OrderDetailsDto() );
source1.setOrderNumber( 11L );
source1.setOrderDate( createDate( "31-08-1982 10:20:56" ) );
source1.setShippingAddress( new ShippingAddressDto() );
source1.getShippingAddress().setCity( "SmallTown" );
source1.getShippingAddress().setHouseNumber( "11a" );
source1.getShippingAddress().setStreet( "Awesome rd" );
source1.getShippingAddress().setCountry( "USA" );
source1.getOrderDetails().setDescription( new ArrayList<String>() );
source1.getOrderDetails().setName( "Shopping list for a Mapper" );
source1.getOrderDetails().getDescription().add( "1 MapStruct" );
source1.getOrderDetails().getDescription().add( "3 Lines of Code" );
source1.getOrderDetails().getDescription().add( "1 Dose of Luck" );
source1.getOrderDetails().setStatus( OrderStatusDto.ORDERED );
// map to JAXB
OrderType target = mapper.targetToSource( source1 );
// do a pretty print
ObjectFactory of = new ObjectFactory();
System.out.println( toXml( of.createOrder( target ) ) );
// map back from JAXB
OrderDto source2 = mapper.sourceToTarget( target );
// verify that source1 and source 2 are equal
assertThat( source2.getOrderNumber() ).isEqualTo( source1.getOrderNumber() );
assertThat( source2.getOrderDate() ).isEqualTo( source1.getOrderDate() );
assertThat( source2.getOrderDetails().getDescription().size() ).isEqualTo(
source1.getOrderDetails().getDescription().size()
);
assertThat( source2.getOrderDetails().getDescription().get( 0 ) ).isEqualTo(
source1.getOrderDetails().getDescription().get( 0 )
);
assertThat( source2.getOrderDetails().getDescription().get( 1 ) ).isEqualTo(
source1.getOrderDetails().getDescription().get( 1 )
);
assertThat( source2.getOrderDetails().getDescription().get( 2 ) ).isEqualTo(
source1.getOrderDetails().getDescription().get( 2 )
);
assertThat( source2.getOrderDetails().getName() ).isEqualTo( source1.getOrderDetails().getName() );
assertThat( source2.getOrderDetails().getStatus() ).isEqualTo( source1.getOrderDetails().getStatus() );
}
@Test
public void underscores() throws ParseException, JAXBException {
SourceTargetMapper mapper = SourceTargetMapper.INSTANCE;
SubTypeDto source1 = new SubTypeDto();
source1.setInheritedCamelCase("InheritedCamelCase");
source1.setInheritedUnderscore("InheritedUnderscore");
source1.setDeclaredCamelCase("DeclaredCamelCase");
source1.setDeclaredUnderscore("DeclaredUnderscore");
SubType target = mapper.dtoToSubType( source1 );
SubTypeDto source2 = mapper.subTypeToDto( target );
assertThat( source2.getInheritedCamelCase() ).isEqualTo( source1.getInheritedCamelCase() );
assertThat( source2.getInheritedUnderscore() ).isEqualTo( source1.getInheritedUnderscore() );
assertThat( source2.getDeclaredCamelCase() ).isEqualTo( source1.getDeclaredCamelCase() );
assertThat( source2.getDeclaredUnderscore() ).isEqualTo( source1.getDeclaredUnderscore() );
}
private Date createDate(String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat( "dd-M-yyyy hh:mm:ss" );
return sdf.parse( date );
}
private String toXml(JAXBElement<?> element) throws JAXBException {
JAXBContext jc = JAXBContext.newInstance( element.getValue().getClass() );
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
ByteArrayOutputStream baos = new ByteArrayOutputStream();
marshaller.marshal( element, baos );
return baos.toString();
}
}

View File

@ -51,7 +51,7 @@
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.2</version>
<version>${jaxb-runtime.version}</version>
</dependency>
</dependencies>
</plugin>
@ -66,14 +66,16 @@
</activation>
<dependencies>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.2</version>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.2</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
</dependencies>
</profile>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright MapStruct Authors.
Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>recordsCrossModuleInterfaceTest</artifactId>
<groupId>org.mapstruct</groupId>
<version>1.0.0</version>
</parent>
<artifactId>records-cross-module-1</artifactId>
</project>

View File

@ -0,0 +1,10 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.records.module1;
public interface NestedInterface {
String field();
}

View File

@ -0,0 +1,10 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.records.module1;
public interface RootInterface {
NestedInterface nested();
}

View File

@ -0,0 +1,11 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.records.module1;
public record SourceNestedRecord(
String field
) implements NestedInterface {
}

View File

@ -0,0 +1,11 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.records.module1;
public record SourceRootRecord(
SourceNestedRecord nested
) implements RootInterface {
}

View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright MapStruct Authors.
Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>recordsCrossModuleInterfaceTest</artifactId>
<groupId>org.mapstruct</groupId>
<version>1.0.0</version>
</parent>
<artifactId>records-cross-module-2</artifactId>
<dependencies>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>records-cross-module-1</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,18 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.records.module2;
import org.mapstruct.itest.records.module1.SourceRootRecord;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper
public interface RecordInterfaceIssueMapper {
RecordInterfaceIssueMapper INSTANCE = Mappers.getMapper(RecordInterfaceIssueMapper.class);
TargetRootRecord map(SourceRootRecord source);
}

View File

@ -0,0 +1,11 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.records.module2;
public record TargetNestedRecord(
String field
) {
}

View File

@ -0,0 +1,11 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.records.module2;
public record TargetRootRecord(
TargetNestedRecord nested
) {
}

View File

@ -0,0 +1,26 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.records.module2;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.mapstruct.itest.records.module1.SourceRootRecord;
import org.mapstruct.itest.records.module1.SourceNestedRecord;
public class RecordsTest {
@Test
public void shouldMap() {
SourceRootRecord source = new SourceRootRecord( new SourceNestedRecord( "test" ) );
TargetRootRecord target = RecordInterfaceIssueMapper.INSTANCE.map( source );
assertThat( target ).isNotNull();
assertThat( target.nested() ).isNotNull();
assertThat( target.nested().field() ).isEqualTo( "test" );
}
}

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright MapStruct Authors.
Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-it-parent</artifactId>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>recordsCrossModuleInterfaceTest</artifactId>
<packaging>pom</packaging>
<modules>
<module>module-1</module>
<module>module-2</module>
</modules>
</project>

View File

@ -0,0 +1,21 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.records;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Filip Hrisafov
*/
@Documented
@Target(ElementType.CONSTRUCTOR)
@Retention(RetentionPolicy.SOURCE)
public @interface Default {
}

View File

@ -0,0 +1,15 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.records;
import java.util.List;
/**
* @author Oliver Erhart
*/
public record Task( String id, Long number ) {
}

View File

@ -0,0 +1,20 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.records;
import java.util.List;
/**
* @author Oliver Erhart
*/
public record TaskDto(String id, Long number) {
@Default
TaskDto(String id) {
this( id, 1L );
}
}

View File

@ -0,0 +1,22 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.records;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
import org.mapstruct.factory.Mappers;
/**
* @author Oliver Erhart
*/
@Mapper(unmappedTargetPolicy = ReportingPolicy.ERROR)
public interface TaskMapper {
TaskMapper INSTANCE = Mappers.getMapper( TaskMapper.class );
TaskDto toRecord(Task source);
}

View File

@ -0,0 +1,13 @@
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.records.nested;
/**
* @author Filip Hrisafov
*/
public record Address(String street, String city) {
}

Some files were not shown because too many files have changed in this diff Show More