Search code examples
javajhipsterdtomapstruct

ChildDTO into ParentDTO in JHIPSTER with mapstruct


I have this entities

    entity Employee {
    firstName String
    lastName String
}

entity Role {
    Name String
}

relationship OneToMany {
    Employee{role} to Role{employee required}
}

And i want to return in the ParentDTO something like this

{
    "id": 1,
    "firstName": "John",
    "lastName": "Doe",
    "roles": 
            [
                {
                    "id": 1                    
                    "name": "Admin"
                },
                {
                    "id": 2
                    "name": "Collector"
                }
            ]   
}

I don't know how to do it and i want to learn. Can please someone tell me how to do it manually or automatically and what to change specifically Iam new to jhipster and mapstruct. Thanks and sorry for disturbing.


Solution

  • Have a look at A unidirectional one-to-many relationship. This is what you have defined but it is not supported as-is. From a DB perspective the entity of which there are many needs to keep track of the one it is associated with.

    You probably need to review that entire page, but they recommend a bi-directional relationship:

    relationship OneToMany { Owner{car} to Car{owner required}

    I made the owner required so that the fake data would be generated. Remove it if cars can be created without owners.

    Adding the DTO option automatically creates the services. You will need to modify the OwnerDTO to add the cars attribute. You will then need to modify the OwnerMapper to add in the cars, by getting them from the CarRepository to which you need to add findByOwner.

    This should help, although it doesn't follow the same pattern as the latest generated code: https://www.jhipster.tech/using-dtos/#advanced-mapstruct-usage

    Correction: When children are not appearing for domain entities, that is just the default Lazy loading. You can change it by adding the fetch type: e.g.

    @OneToMany(mappedBy = "owner", fetch = FetchType.EAGER)