【问题标题】:Fetch joined table when creating a new entity创建新实体时获取连接表
【发布时间】:2020-03-29 13:11:33
【问题描述】:

我有一个 Customers 表,其中包含 AddressEmbedded

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

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

但我收到了 mapstruct 无法生成 setCountry 的错误。

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

以下是实体定义:

    @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;
    }

【问题讨论】:

  • 您将无法将String 传递给AddressEmbedded.setCountry。看起来您需要通过 ID (country) 查找 CountryEntity,然后将其传递给 AddressEmbedded.setCountry
  • 在 setter 中查找?
  • 我个人认为将任何逻辑置于 getter/setter 是不好的做法。相关话题:stackoverflow.com/questions/44600536/…
  • 当然,这就是我问这个问题的原因,我不想在setter中添加db调用。

标签: java spring-boot jpa entity


【解决方案1】:

这已通过 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,因为在我调用它之前,我确认我有一个存在的国家。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    相关资源
    最近更新 更多