我做了一些研究,這個問題被問到沒有有效的解決方案,基本上我有一個連接的業務,當斷開連接時,記錄被保留但標有斷開連接日期,我希望 jpa 只提取當前活動記錄(或沒有)。
@Entity
@Table(name = "business", schema = "public")
public class Business {
...
@JsonManagedReference
@OneToOne(mappedBy = "business", cascade = CascadeType.ALL)
private Connection connection;
...
}
對于連接,我放置了“OneToOne”,因為應該總是有一個或沒有活動連接,我希望結果是一個物件而不是陣列,但從技術上講,這是不正確的,我也不知道如何解決這個問題。
有沒有辦法以某種方式在連接上添加條件?這并不少見。
uj5u.com熱心網友回復:
正確,您不能使用 an OneToOne,您需要將 a@OneToMany與 a一起使用Set<Connection>
但是您可以將Set<Connection>與 hibernate Where-annotation結合使用并“隱藏”該集合,并且只回傳活動的Connection(或空的)
@Entity
class Business {
...
@OneToMany(mappedBy = "business", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@Where(clause = "active = true") // <--- only load the active connection if any
private Set<Connection> connections = new HashSet<>();
@JsonManagedReference // <--- reference to the active connection
public Connection getConnection() {
return connections.stream().findFirst().orElse(null);
}
public void setConnection(Connection connection) {
connections.add(connection);
}
// other getters/setters, but no getter for Set<Connection> connections
}
評論:
或者,@Where(clause = "disconnected is null")可以在 where 子句中使用disconnected-date 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/345748.html
