对此我需要一些帮助:)
我有一个Abstract模型,它为每个实体提供ID,创建时间和更新时间:
@MappedSuperclass
public abstract class AbstractModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY, generator = "native")
@Column(name = "ID", updatable = false, nullable = false)
protected Long id;
@Column(updatable = false)
@CreationTimestamp
protected Timestamp creationTime;
@UpdateTimestamp
protected Timestamp updateTime;
//getters and setters
实体样本:
@Entity
@Table(name = "CUSTOMERS", uniqueConstraints={@UniqueConstraint(columnNames = {"fiscalNumber" , "phoneNumber", "email"})})
public class Customer extends AbstractModel {
//other properties
//getters and setters
}
控制器:
public String saveCustomer(@Valid @ModelAttribute("customer") CustomerDto customerDto, BindingResult result, Model model) {
...
customerService.save(customerMapper.toModel(customerDto));
model.addAttribute("customer", customerDto);
return "redirect:/customer/list";
}
Dao的实现:
public Customer save(Customer model) ... {
if (model.getId() == null) {
return (Customer) session.merge(model);
}
...
}
发生的事情是,每次我尝试使用model.getId获取ID时,即使我使用Objects.isNull(model.getId())或将其包装在Optional上,我都会得到nullPointerException
如果我尝试相同的操作,但是要获得creationTime(model.getCreationTime()),它会按预期工作。
其他信息: NPE仅在将modelDto(customerDto)转换为model(customer)后出现,并且仅用于ID。目前,我正在使用modelmapper,但我也尝试过使用mapstruct,但出现了相同的错误。我还尝试了各种类型的转化策略。
感谢您的关注:)