我有一个Bid实体,定义如下
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@Entity
@Table(name = "bid_details")
public class Bid {
private enum STATUS { INITIATED, DRAFT, COMPLETED }
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, updatable = false)
private Integer id;
@Column(name = "govt_bid_id", nullable = false)
private String govtBidNumber;
@Temporal(TemporalType.DATE)
@Column(name = "release_date", nullable = false)
@JsonFormat(pattern = "dd-MM-yyyy")
private Date releaseDate;
@ManyToOne(optional = false)
@JoinColumn(name = "created_by", referencedColumnName = "id", updatable = false, nullable = false)
private User createdBy;
@Temporal(TemporalType.DATE)
@Column(name = "created_date", nullable = false)
@CreationTimestamp
private Date createdDate;
@ManyToOne
@JoinColumn(name = "updated_by", referencedColumnName = "id", updatable = false, nullable = false)
private User updatedBy;
@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false)
private STATUS status;
@Column(name = "avg_turnover")
private String avgTurnover;
@Convert(converter = StringListConverter.class)
@Column(name = "docs_required", columnDefinition = "json")
private List<String> docsRequired;
@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false)
private STATUS status;
}
bid_details
表中存在相应的列。我的出价存储库定义如下:public interface BidRepository extends JpaRepository<Bid, Integer> {
}
现在,当我尝试使用
findById
通过id访问数据时,会抛出No Value Present
异常,而如果我尝试使用findAllById
访问数据,则会得到正确的结果。无法弄清楚是什么导致了这种奇怪的行为。另外,如果我先执行
findAll
然后执行findById
,则给出正确的结果。我正在使用spring-boot版本2.1.1
以下是实体保存在数据库中的代码
public Bid addBid(BidRequest bidRequest) {
User user = userRepository.findById(bidRequest.getCreatedBy()).get();
Bid bid = new Bid();
modelMapper.map(bidRequest, bid);
bid.setCreatedBy(user);
return bidRepository.save(bid);
}
BidRequest类如下:
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
public class BidRequest {
private String govtBidNumber;
@Temporal(TemporalType.DATE)
@JsonFormat(pattern = "yyyy-MM-dd")
private Date releaseDate;
@Temporal(TemporalType.DATE)
private Date endDate;
private int createdBy;
@Temporal(TemporalType.DATE)
@JsonFormat(pattern = "yyyy-MM-dd")
private Date createdDate;
private int updatedBy;
private String status;
private List<String> docsRequired;
}
最佳答案
您是否尝试过orElse
这样
findById(id).orElse(null);
因为
findById
返回一个Optional
对象,所以您必须在orElse()
之后写findById()