我擁有的 2 個物體:Country和User
@Entity(name = "Country")
@Table(name = "countries")
public class Country {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(cascade = CascadeType.ALL,
orphanRemoval = true)
private List<User> users = new ArrayList<>();
}
@Entity(name = "User")
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private boolean removed;
}
物體User有一個屬性、removed型別boolean,我們需要跳過/忽略所有User具有removedequals 的true。
Hibernate 是否提供任何合適的機制來實作我的目標?
PS:谷歌說可能我可以使用注釋,如: @JoinColumn, @JoinColumnOrFormula,但根據我讀過的檔案,上面提到的注釋屬于@ManyToOne場景,在我的特殊情況下我有@OneToMany關系。
uj5u.com熱心網友回復:
使用 hibernate,@Where在物體上使用應該可以解決問題。這將阻止加載已洗掉標志設定為 的任何用戶true。您可能會在hibernate 檔案中找到更多資訊
如果你只希望這個在集合上,你可以在關系上添加注釋
@Entity(name = "Country")
@Table(name = "countries")
public class Country {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(cascade = CascadeType.ALL,
orphanRemoval = true)
@Where( clause = "removed = false" ) // <- here
private List<User> users = new ArrayList<>();
}
或者,如果您根本不想加載任何已洗掉的用戶,則可以將注釋添加到類中。
@Entity(name = "User")
@Table(name = "users")
@Where( clause = "removed = false" ) // <- here
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private boolean removed;
}
需要注意的是,我沒有使用過這個,但我假設如果您有其他物體鏈接到一個將標志設定為 true 的用戶,您將需要更新注釋以允許空值。
例如,想象一個電子商務站點,一個訂單鏈接到一個用戶。加載鏈接到已洗掉用戶的訂單將失敗,或者您可以修改注釋,使其回傳null用戶的訂單。我希望這是有道理的!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/311288.html
