创建新实体时获取加入 table

Fetch joined table when creating a new entity

我有一个 Customers table,里面有 AddressEmbedded

我还有一个硬编码的 table Countries,其中我已经为每个国家/地区设置了一个区域,国家/地区是主键。

我想加入 AddressEmbeddedCountries,所以我使用 ManyToOne 并将 CountryEntity 放入 AddressEmbedded

但是我收到一个错误,mapstruct 无法生成 setCountry

那么问题来了,我该如何制作AddressEmbedded.setCountry(string country)? 它应该调用数据库以获取该国家/地区的相应区域,但在 setter 中添加数据库调用似乎是错误的。

以下是实体定义:

    @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    @Data
    @Embeddable
    public class AddressEmbedded {

        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "country")
        private CountryEntity country;
    }
    @Data
    @Entity
    @Table(name = "Countries")
    public class CountryEntity {

        @Id
        @Column(name = "country")
        private String country;

        @Column(name = "region")
        private String region;
    }
    @Data
    @Entity
    @Table(name = "Customers")
    public class CustomerEntity {
        @Embedded
        private AddressEmbedded address;
    }

这已通过 mapstruct 映射解决

    @Mappings(
            @Mapping(target = "address.country", source = "countryEntity")
    )
    CustomerEntity fromSubmitCustomerDetailsRequestToCustomerEntity(SubmitCustomerDetailsRequest request, CountryEntity countryEntity);

    @Mappings(
            @Mapping(target = "address.country", source = "customerEntity.address.country.country")
    )
    GetCustomerDetailsResponse fromCustomerEntityToGetCustomerDetailsResponse(CustomerEntity customerEntity);

我在 fromSubmitCustomerDetailsRequestToCustomerEntity 中有 CountryEntity 因为在我调用它之前我验证了我有一个存在的国家。