我有一个简单的问题-但我认为“我站在地铁上”。 我有一个带有JPA,Modelmapper,实体和DTO的spring boot rest api。 但是映射不起作用。
实体:
@Getter
@Setter
@MappedSuperclass
public class AbstractEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
}
@Getter
@Setter
@Entity(name = "contacts")
public class Contact extends AbstractEntity {
@NotBlank
private String firstName;
@NotBlank
private String lastName;
@Valid
@OneToMany(mappedBy = "contact", cascade = CascadeType.ALL, orphanRemoval = true)
private List<PhoneNumber> phoneNumberList;
}
@Getter
@Setter
@Entity(name = "phone_numbers")
public class PhoneNumber extends AbstractEntity {
@NotBlank
private String label;
@NotBlank
private String number;
@ManyToOne
@JoinColumn(name = "contact_id", referencedColumnName = "id")
@Setter(value = AccessLevel.NONE)
private Contact contact;
}
DTO:
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ContactDTO {
private Long id;
private String firstName;
private String lastName;
List<PhoneNumberDTO> phoneNumberDTOList = new ArrayList<>();
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PhoneNumberDTO {
private Long id;
private String label;
private String number;
}
我的ModelMapperConfig:
@Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration()
.setFieldMatchingEnabled(true)
.setFieldAccessLevel(AccessLevel.PRIVATE);
return modelMapper;
}
回购:
public interface ContactRepository extends JpaRepository<Contact, Long{
}
服务(仅创建方法):
@Override
public ContactDTO createOne(ContactDTO contactDTO) {
Contact contact = modelMapper.map(contactDTO, Contact.class);
contactRepository.save(contact);
return contactDTO;
}
这是使用多个电话号码保留联系人的正确方法吗?
如何创建一个简单的映射?
如果我要坚持下去,就会出现错误:
Column 'contact_id' cannot be null