[英]How to map optional ID field to entity?
I have entity called Franchise and this entity looks like this:我有一个名为 Franchise 的实体,这个实体看起来像这样:
@Data
@Entity
@Table(name = "franchises")
public class Franchise {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Enumerated(EnumType.STRING)
private FranchiseType type;
@ToString.Exclude
@EqualsAndHashCode.Exclude
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "country_id")
private Country country;
}
I have following api endpoint for creating new Franchise entity: POST /api/franchise
And fields that I need to send are: name
, type
and countryId
.我有以下 api 端点来创建新的特许经营实体:
POST /api/franchise
我需要发送的字段是: name
, type
和countryId
。 countryId
is optional field and can be null in the database (column country_id
). countryId
是可选字段,可以是数据库中的 null( country_id
列)。
I am using mapstruct to map CreateFranchiseDTO
to Franchise
:我正在使用 mapstruct 到 map
CreateFranchiseDTO
到Franchise
:
@Data
public class CreateFranchiseDTO {
private String name;
private String type;
private Long countryId;
}
@Mapper(componentModel = "spring")
public interface FranchiseDTOMapper {
@Mapping(source = "countryId", target = "country.id")
Franchise fromCreateFranchiseDTO(CreateFranchiseDTO dto);
}
When I call above mentioned api endpoint with countryId
set to some integer (which exists in countries
table) everythng works.当我调用上面提到的 api 端点时,
countryId
设置为某个 integer(存在于countries
表中),一切正常。 But if I call endpoint without countryId
field in request body and when the following code executes I get exception object references an unsaved transient instance
:但是,如果我在请求正文中调用没有
countryId
字段的端点,并且当执行以下代码时,我会收到异常object references an unsaved transient instance
:
Franchise franchise = franchiseDTOMapper.fromCreateFranchiseDTO(dto);
franchiseRepository.save(franchise);
When I look at the debugger I can see that franchise.getCountry()
is equal to Country
object with all fields set to NULL or zero/false (default values for primitives)当我查看调试器时,我可以看到 Franchise.getCountry
franchise.getCountry()
等于Country
object,所有字段都设置为 NULL 或零/假(原语的默认值)
I have few options to solve this:我有几个选择来解决这个问题:
@AfterMapping
and check for franchise.getCountry().getId() == null
@AfterMapping
并检查franchise.getCountry().getId() == null
Country longToCountry(Long id)
Country longToCountry(Long id)
But it seems to me that I am missing something or I am wrong.但在我看来,我错过了什么或者我错了。 So how do I map an optional ID (relation) to field using mapstruct?
那么如何使用mapstruct map 到字段的可选ID(关系)?
If I understand correctly, you have the same problem as this person .如果我理解正确,你和这个人有同样的问题。
What seems to have worked for that person was to use optional = true
:似乎对那个人有用的是使用
optional = true
:
@ManyToOne(optional = true, fetch = FetchType.LAZY)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.