我有一個TimelineEntity物體,它使用HoTimelineType帶有自定義整數值的列舉。該自定義整數值存盤在資料庫中。通過使用 @PostLoad 和 @PrePersist 注解實作
Sprint JPA Repository 用于保存和獲取物體。
這是問題:
@Entity
@Table(name = TABLE_NAME)
@IdClass(TimelineKey.class)
public class TimelineEntity {
public interface Persistence {
String TABLE_NAME = "timelines";
}
@Id
@Column(name = "node_id")
private Long nodeId;
@Id
@Column(name = "timeline_id")
private Long timelineId;
@Column(name = "ho_timeline_type")
private Integer hoTimelineTypeValue;
@Transient
private HoTimelineType hoTimelineType;
public Long getNodeId() {
return nodeId;
}
public void setNodeId(Long nodeId) {
this.nodeId = nodeId;
}
public Long getTimelineId() {
return timelineId;
}
public void setTimelineId(Long timelineId) {
this.timelineId = timelineId;
}
public HoTimelineType getHoTimelineType() {
return hoTimelineType;
}
public void setHoTimelineType(HoTimelineType hoTimelineType) {
this.hoTimelineType = hoTimelineType;
}
public Integer getHoTimelineTypeValue() {
return hoTimelineTypeValue;
}
public void setHoTimelineTypeValue(Integer hoTimelineTypeValue) {
this.hoTimelineTypeValue = hoTimelineTypeValue;
}
@PostLoad
private void postLoad() {
this.hoTimelineType = HoTimelineType.of(hoTimelineTypeValue);
}
@PrePersist
private void prePersist() {
this.hoTimelineTypeValue = hoTimelineType.getValue();
}
}
@Eager
public interface TimelineEntityRepository extends JpaRepository<TimelineEntity, TimelineKey> {
List<TimelineEntity> findByNodeId(Long nodeId);
}
@Autowired
private TimelineEntityRepository timelineEntityRepository;
...
TimelineEntity newTE = new TimelineEntity();
newTE.setNodeId(10L);
newTE.setTimelineId(22L);
newTE.setHoTimelineType(HoTimelineType.TYPE_1);
newTE = timelineEntityRepository.save(newTE);
當newTE物體被保存,prePersist被呼叫,在這個方法中,它hoTimelineType是空的,我得到 NPE。nodeId并且timelineId不是空值。如果我在最后一行使用除錯器,在 之外prePersist,我看到它hoTimelineType具有我之前設定的值。
當我加載物體并插入測驗資料時,一切正常,并且兩者hoTimelineType都hoTimelineTypeValue沒有可為空的值。
我跳過了TimelineKey和的代碼HoTimelineType來簡化示例。如果需要,可以添加它。
什么可以重置hoTimelineType?我想念什么?
uj5u.com熱心網友回復:
似乎沒有辦法控制spring jpa存盤庫代理的保存行為。
問題的可能解決方案:
- 通過
javax.persistence.Converter. 很清楚,物體的結構很簡單。可以確認它適用于 Spring Jpa Repository 生成。 hoTimelineTypeValue在保存物體之前顯式設定。容易出錯的解決方案。hoTimelineTypeValue每次保存物體時,都必須考慮和之間的區別hoTimelineType。- 您可以豐富物體類的 setter 和 getter,以明確控制欄位之間的一致性。它使物體類的實作不那么明顯。你會得到更復雜的解決方案。結果是容易出錯的解決方案。也不推薦它。
#2 和 #3 的缺點的原因我不提供示例。這沒有道理。
可以在此處找到解決方案#1 的示例:使用 JPA 2.1 @Converter Annotation
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/477901.html
上一篇:帶有聚合函式的休眠子查詢問題
