mapstruct / mapstruct/mapstruct
@SubclassMapping selecting implementation class based on source field value
Nobody has claimed this yet.
- Dominant language
- Java
- Stars
- 7.7k
- Forks
- 1.1k
- PR merge metrics
- No merged PRs in 30d
Description
### Use case
It is common practice saving multiple sub-classes into one database tables. E.g.:
I have a db entity Contact with type field value
```kotlin
@Entity
@Table(name = CONTACTS_TABLE)
open class ContactEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = 0
@Column(name = CONTACT_TYPE_COLUMN, nullable = false)
var type: ContactType = ContactType.BUSINESS
}
```
My domain model Contact is abstract and can have two implementations: BusinessContact and NaturalPersonContact:
```kotlin
sealed interface Contact {
val id: Long
}
data class BusinessContact(
override val id: Long,
val businessName: String,
) : Contact
data class NaturalPersonContact(
override val id: Long,
val firstName: String,
val lastName: String,
) : Contact
```
Trying to define a Mapper with `@SubclassMapping` has no option to add logic to it based on type property:
```kotlin
@SubclassMapping(target = BusinessContact::class, source = ContactEntity::class)
@SubclassMapping(target = NaturalPersonContact::class, source = ContactEntity::class)
fun entityToDomainModel(entity: ContactEntity): Contact
```
### Generated Code
_No response_
### Possible workarounds
None known
### MapStruct Version
implementation("org.mapstruct:mapstruct:1.5.5.Final")
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by examining how @SubclassMapping is processed for the ContactEntity-to-Contact mapper described in the issue, including the MapStruct 1.5.5.Final behavior. Done should support selecting BusinessContact or NaturalPersonContact from the source type property and include coverage for that generated mapping.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java, kotlin
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 30/100