所以我有三個物體。A、B 和 P(P 是超類)。它們是這樣的:
@MappedSuperclass
public class P {
@Id
@GeneratedValue
public Long id;
public LocalDateTime lastUpdated = LocalDateTime.now();
//Other fileds, getters, setters, etc...
}
@Entity
@Table
public class A extends P {
//fileds, getters, setters, etc..
}
@Entity
@Table
public class B extends P {
//fileds, getters, setters, etc..
}
我有物體 A 和 B 的存盤庫
@Repository
public interface ARepository extends JpaRepository<A, Long> {
}
B 存盤庫
@Repository
public interface BRepository extends JpaRepository<B, Long> {
}
當我保存物體時,我必須在lastUpdated 每次 save() 之前呼叫 setter 方法來更新欄位,如下所示:
@Service
public class AService {
private final ARepository aRepository;
@Autowired
public AService(ARepository aRepository){
this.aRepository= aRepository;
}
public A doSomethingToA(A a){
//Run some logic here...
a.setLastUpdated(LocalDateTime.now()); // I dont want this line one very update method of every entity. is there a way to put it inside the save() method (overriding or something), or any other solution to this?
return aRepository.save(a);
}
}
這里的問題是,如果我有 200 個擴展類 P 的物體,我必須在setLastUpdated()每次呼叫 save() 之前呼叫這個方法。無論如何我可以把這條線放在保存方法中嗎?(無需覆寫擴展 P 的 200 個物體的所有 200 個存盤庫上的保存)。
uj5u.com熱心網友回復:
EntityListener你可以在你的類 P 上使用 Hibernate :
public class P {
@PreUpdate
@PrePersist
public void setLastUpdated() {
lastUpdated = LocalDateTime.now();
}
}
關于它的官方檔案:https ://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html/listeners.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/459158.html
